我想编写一个 servlet 来包装一组资源并需要使用基本的 HTTP 身份验证来保护它们;在提供文件之前,将根据后端数据库检查提交的用户名/密码。
有人有这方面的工作例子吗?我在http://www.coderanch.com/t/352345/Servlets/java/HTTP-basic-authentication-Web-Applications尝试了示例,但它一直IllegalStateException
在sendError
调用中返回一个。
我想编写一个 servlet 来包装一组资源并需要使用基本的 HTTP 身份验证来保护它们;在提供文件之前,将根据后端数据库检查提交的用户名/密码。
有人有这方面的工作例子吗?我在http://www.coderanch.com/t/352345/Servlets/java/HTTP-basic-authentication-Web-Applications尝试了示例,但它一直IllegalStateException
在sendError
调用中返回一个。
Here is some code that returns a Credential object (bean object holding login and password).
public Credentials credentialsWithBasicAuthentication(HttpServletRequest req) {
String authHeader = req.getHeader("Authorization");
if (authHeader != null) {
StringTokenizer st = new StringTokenizer(authHeader);
if (st.hasMoreTokens()) {
String basic = st.nextToken();
if (basic.equalsIgnoreCase("Basic")) {
try {
String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
LOG.debug("Credentials: " + credentials);
int p = credentials.indexOf(":");
if (p != -1) {
String login = credentials.substring(0, p).trim();
String password = credentials.substring(p + 1).trim();
return new Credentials(login, password);
} else {
LOG.error("Invalid authentication token");
}
} catch (UnsupportedEncodingException e) {
LOG.warn("Couldn't retrieve authentication", e);
}
}
}
}
return null;
}
It works well, even with a password as funky as :&=/?é$£.
Here is a basic unit test for the class, using jMock:
public void testCredentialsWithBasicAuthentication() {
// Setup
final HttpServletRequest request = context.mock(HttpServletRequest.class);
AuthentificationHelper helper = new AuthentificationHelper();
String login = "mickael";
String password = ":&=/?é$£";
String base64Hash = Base64.encodeString(login + ":" + password);
final String authHeader = "Basic " + base64Hash;
// Expectations
context.checking(new Expectations() {
{
oneOf (request).getHeader("Authorization");
will(returnValue(authHeader));
}
});
// Execute
Credentials credentials = helper.credentialsWithBasicAuthentication(request);
// Verify
assertNotNull(credentials);
assertEquals(login, credentials.getLogin());
assertEquals(password, credentials.getPassword());
context.assertIsSatisfied();
}