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

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

 

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

 

Java代码   收藏代码
  1. @Override  
  2. public void init(Context context, Request request, Response response) {  
  3.     super.init(context, request, response);  
  4.     ChallengeResponse challengeResponse = request.getChallengeResponse();  
  5.     if(challengeResponse != null){  
  6.         String userName = challengeResponse.getIdentifier();  
  7.         String password = new String(request.getChallengeResponse().getSecret());  
  8.           
  9.         //here is to get password from database through user name, suppose the password is "tiger"  
  10.         if(!"tiger".equals(password)){  
  11.             response.setEntity("User name and password are not match", MediaType.TEXT_PLAIN);  
  12.             setModifiable(false);  
  13.         }  
  14.     }  
  15.       
  16.     customerId = (String) request.getAttributes().get("customerId");  
  17. }  

 

 

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

 

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

 

Java代码   收藏代码
  1. Request request = new Request(Method.POST, "http://localhost:8080/restlet/resources/customers/1");  
  2.   
  3. ChallengeScheme scheme = ChallengeScheme.HTTP_BASIC;  
  4.   
  5. ChallengeResponse authentication = new ChallengeResponse(scheme, "scott""123");  
  6. request.setChallengeResponse(authentication);  
  7.   
  8. Client client = new Client(Protocol.HTTP);  
  9. Response response = client.handle(request);  
  10. if (response.getStatus().isSuccess()) {         
  11.     try {  
  12.         response.getEntity().write(System.out);  
  13.     } catch (IOException e) {  
  14.         e.printStackTrace();  
  15.     }  
  16. }else if (response.getStatus().equals(Status.CLIENT_ERROR_UNAUTHORIZED)) {      
  17.     System.out.println("Access authorized by the server, " + "check your credentials");  
  18. }else {     
  19.     System.out.println("An unexpected status was returned: "+ response.getStatus());  
  20. }  

 

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

 

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

猜你喜欢

转载自chenjianfei2016.iteye.com/blog/2355186
今日推荐