我们设定一个场景:一个信息系统是基于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方法。
分享到:
相关推荐
一个简单的Restlet开发框架的Basic认证的例子
NULL 博文链接:https://ajaxcn.iteye.com/blog/438237
restlet相关文档
restlet项目
Restlet与Spring 集成
org.restlet.jar
NULL 博文链接:https://sb33060418.iteye.com/blog/1768621
Restlet Client插件是一款运行在chrome内核浏览器上的Web服务测试插件,该插件主要用于测试各种Web服务,能查看网站基本信息、浏览网页代码并能发送HTTP请求来测试网站Web服务,同时支持自动化API场景。用户在安装了...
restlet2.1学习笔记项目代码
资源里面包含了Restlet从入门到高级的开发过程,对学习Restlet有很大的帮助
使用restlet实现了最简单的restful webservice,可以直接部署运行。可以作为restful webservice开发的基础环境。
RESTLET开发实例(二)使用Component、Application的REST服务
Restlet所需要的所有jar包 一次下载,以后高枕无忧!
restlet入门helloworld示例
RESTLET框架学习书籍
本文是对Restlet官方教程http://restlet.com/learn/tutorial/2.2/的中文翻译。
restlet入门示例,实现的功能是通过访问web资源,返回一个“hello world”字符串信息。
Restlet2.0用户指南
restlet工程示例,restlet工程小例子