`
ajax
  • 浏览: 252134 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Restlet实战(八)访问敏感资源之基础认证(Basic)

    博客分类:
  • REST
阅读更多

我们设定一个场景:一个信息系统是基于Rest风格的,另外与一套CRM系统通信,当CRM中维护的Customer资料有变动或者创建一个新的Customer,则与信息系统通信,来更新或者创建信息系统的Customer。

 

基于上述我们假设的场景,下面从代码上来看看如何在Restlet里面实现Basic 认证。假设认证发生在当一个request是为了修改Customer信息。仍旧基于此系列前面文章的代码,在Customer Resource里面我们加一段代码:

 

	@Override
	public void init(Context context, Request request, Response response) {
		super.init(context, request, response);
		ChallengeResponse challengeResponse = request.getChallengeResponse();
		if(challengeResponse != null){
			String userName = challengeResponse.getIdentifier();
			String password = new String(request.getChallengeResponse().getSecret());
			
			//here is to get password from database through user name, suppose the password is "tiger"
			if(!"tiger".equals(password)){
				response.setEntity("User name and password are not match", MediaType.TEXT_PLAIN);
				setModifiable(false);
			}
		}
		
		customerId = (String) request.getAttributes().get("customerId");
	}

 

 

客户端的请求是要修改一个customer, 所以,当用户名和密码校验不通过时,则设置setModifiable的值为false,则post对应的acceptRepresentation方法就会被禁止调用。

 

使用Restlet作为客户端来测试上述代码:

 

	Request request = new Request(Method.POST, "http://localhost:8080/restlet/resources/customers/1");
	
	ChallengeScheme scheme = ChallengeScheme.HTTP_BASIC;
	
	ChallengeResponse authentication = new ChallengeResponse(scheme, "scott", "123");
	request.setChallengeResponse(authentication);
	
	Client client = new Client(Protocol.HTTP);
	Response response = client.handle(request);
	if (response.getStatus().isSuccess()) {       
		try {
			response.getEntity().write(System.out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}else if (response.getStatus().equals(Status.CLIENT_ERROR_UNAUTHORIZED)) {    
		System.out.println("Access authorized by the server, " + "check your credentials");
	}else {   
		System.out.println("An unexpected status was returned: "+ response.getStatus());
	}

 

 通过测试,能发现在Resource里面的init方法能拦截到客户端发送请求时的用户名和密码,然后到数据库去取出正确的密码做一比较,如果不符合,就不作update操作。

 

值得注意的是,这里不能使用Httpclient的最新版本进行测试,因为Restlet1.1.5版本不支持Httpclient lib库中的代理信息,所以,如果想用Httpclient测试,请改用restlet1.2或者2.0的版本,这两个版本里面Request类里面增加了getProxyChallengeResponse方法。

 

分享到:
评论
1 楼 nocohol 2009-07-31  
你说明如果密码不匹配,通过设置setModifiable(false)来使post对应的acceptRepresentation方法就会被禁止调用。但是通过我测试,发现DAO里面的updateCustomer还是被调到。也就是说acceptRepresentation没有被禁止掉,因为我们覆盖了allowPost()这个方法,init方法调完之后,这个方法依然会被叫到,如果我注释掉allowPost()方法,客户端使用错误的密码访问时会报An unexpected status was returned: Method Not Allowed (405) - Method Not Allowed。这应该说明acceptRepresentation被禁用了,但是user name and password are not match却没有返回给用户,这是为什么?

相关推荐

Global site tag (gtag.js) - Google Analytics