我正在使用此ContainerRequestFilter來檢查HTTP基本憑據。如何訪問HTTP基本用戶名?
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篩選(我謹用戶名/密碼提取邏輯以它自己的方法)。在過濾器中,我可以以某種方式將提取的用戶名存儲在請求對象的某處,以便將它傳遞給此處理程序?
(順便說一下,有沒有更好的方法來提取比我在過濾器中所做的用戶名和密碼?如果是這樣,讓我知道了評語)
請注意,auth.split(「:」);如果密碼包含冒號則不起作用(rfc2617允許冒號輸入密碼)。你應該auth.split(「:」,2);代替。 – riskop