我们设定一个场景:一个信息系统是基于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方法。