Jersey HTTP认证:如何访问和Jersey restful url中的HTTP认证



我正在用Jersey编写一个rest式web服务,这是示例代码:

@GET
@Produce(MediaType.APPLICATION_JSON)
public String findItems(){
...
}

, findItem的url是localhost:8080/items该方法在执行之前应该验证此url的HTTP身份验证信息(摘要或基本),如何首先从url请求访问身份验证?

我不会把它放在控制器本身,而是放在您希望保护的资源类周围的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
    }
}                   

通常身份验证是由容器处理的,您只需在web.xml中添加相应的约束,以指示应该保护哪些uri以及需要哪种认证。然后在jersey中,你可以从SecurityContext中获得角色和主体信息,你可以注入到你的资源中。

最新更新