[英]How can I access the HTTP Basic username?
I'm using this ContainerRequestFilter to check HTTP Basic credentials. 我正在使用此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;
}
...
}
So by the time I get to this point, I've authenticated the user. 所以当我到达这一点时,我已经对用户进行了身份验证。 Now how I can get the username? 现在我如何获得用户名?
@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 = ???;
}
I suppose I could use HttpContext.getRequest() and do the same thing as in the AuthFilter (I'd move that username/password extraction logic to its own method). 我想我可以使用HttpContext.getRequest()并执行与AuthFilter相同的操作(我将用户名/密码提取逻辑移动到它自己的方法)。 In the filter, can I somehow store the extracted username somewhere in the request object so it gets passed on to this handler? 在过滤器中,我可以以某种方式将提取的用户名存储在请求对象中的某处,以便将其传递给此处理程序吗?
(By the way, is there a better way to extract the username and password than what I've done in the filter? If so, let me know in a comment.) (顺便说一下,有没有比我在过滤器中更好的方法来提取用户名和密码?如果有,请在评论中告诉我。)
Take a look how it's done in a working application: www.s3auth.com . 看看它是如何在一个有效的应用程序中完成的: www.s3auth.com 。 The source code is available at github . 源代码可以在github上找到 。 As you can see on the site, facebook and google authentication mechanisms are used. 正如您在网站上看到的,使用了Facebook和Google身份验证机制。 The application is using JAX-RS/Jersey. 该应用程序使用JAX-RS / Jersey。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.