java – 如何访问HTTP Basic用户名?

我正在使用此ContainerRequestFilter来检查HTTP Basic凭据.

private class Filter implements ResourceFilter, ContainerRequestFilter {

    @Override
    public ContainerRequest filter(ContainerRequest request) {
        String auth = request.getHeaderValue("Authorization");

        if (auth == null || !auth.startsWith("Basic ")) {
            throw new NotAuthorizedException("FAILED\n");
        }

        auth = Base64.base64Decode(auth.substring("Basic ".length()));
        String[] vals = auth.split(":");
        String username = vals[0];
        String password = vals[1];

        boolean validUser = database.Users.validate(username, password);

        if (!validUser) {
            throw new NotAuthorizedException("FAILED\n");
        }

        return request;
    }

    ...

}

所以当我到达这一点时,我已经对用户进行了身份验证.现在我如何获得用户名?

@GET
@Path("some_kind_of_report_or_something")
@Produces(MediaType.TEXT_PLAIN)
public String fetchAReportOrSomething() {
    // At this point, I know that the user has provided good credentials,
    // now I need get the user's username as a String
    String username = ???;
}

我想我可以使用HttpContext.getRequest()并执行与AuthFilter相同的操作(我将用户名/密码提取逻辑移动到它自己的方法).在过滤器中,我可以以某种方式将提取的用户名存储在请求对象中的某处,以便将其传递给此处理程序吗?

(顺便说一下,有没有比我在过滤器中更好的方法来提取用户名和密码?如果有,请在评论中告诉我.)

解决方法:

这篇博客文章应该启发你:
http://plaincode.blogspot.pt/2011/07/openid-authentication-example-in-jersey.html

上一篇:android – Java jersey RESTful webservice请求


下一篇:使用Curl Command使用Jersey,Jackson和json.org/java Parser进行JSON格式化