【问题标题】:Jersey HTTP authentication:How Can I Access and the HTTP authentication in jersey restful url?Jersey HTTP authentication:How Can I Access and the HTTP authentication in jersey restful url?
【发布时间】:2011-12-05 15:05:04
【问题描述】:
我正在用 Jersey 编写一个 Restful 网络服务,这是示例代码:
@GET
@Produce(MediaType.APPLICATION_JSON)
public String findItems(){
...
}
findItem 的 url 是 localhost:8080/items
该方法应在执行前验证此 url 的 http 身份验证信息(摘要或基本),如何首先从 url 请求访问身份验证?
【问题讨论】:
标签:
java
jakarta-ee
jersey
【解决方案1】:
我不会把它放在控制器本身中,而是放在你希望保护的资源类周围的 com.sun.jersey.spi.container.ContainerRequestFilter 中,但应该给你基本的想法。
@Context
private HttpServletRequest request;
@GET
@Produce(MediaType.APPLICATION_JSON)
public String findItems(){
String auth = request.getHeader("authorization");
if (auth != null) {
String basic_prefix = "Basic ";
if (auth.startsWith(basic_prefix)) {
String auth_data = new String(Base64.decode(auth.substring(basic_prefix.length())));
String [] user_and_key = auth_data.split(":", 2);
// user and password available here
} else {
// reject access
}
} else {
// reject access
}
}
【解决方案2】:
通常认证是由容器来处理的,你只需要在web.xml中添加相应的约束来指明哪些Uris应该被保护,需要什么样的认证。然后在 jersey 中,您可以从 SecurityContext 中获取角色和主体信息,您可以将其注入到您的资源中。