我需要在servlet应用程序中执行HTTP身份验证逻辑,而不是将此任务委派给容器。
具体来说,我需要一种方法来获取包含HTTP身份验证头的HttpServletRequest
的标头,并将它们解码为表示所提供凭据的数据结构,然后应用程序可以处理该凭据。应支持基本身份验证和摘要身份验证。
我可以手工编写,这不是太多的苦差事,RFC都有很好的文档记录,但我非常想使用现成的库为我做这件事。
我的第一个想法是Spring Security,但是我可以告诉他将此任务委托给容器(我有点不清楚,这是一个复杂的代码库)。
任何人都知道其他人吗?
答案 0 :(得分:2)
答案 1 :(得分:1)
这是我的解码器:
public static String[] decodeBasicAuth(String authorization) {
if (authorization == null)
throw new RuntimeException("Invalid Authorization String.");
if (authorization.length() < 9)
throw new RuntimeException("Invalid Authorization String.");
if (authorization.length() > 64)
throw new RuntimeException("Invalid Authorization String.");
String s[] = authorization.split("\\s", 3);
if (s.length < 2)
throw new RuntimeException("Invalid Authorization String.");
for (int i = 0; i < s.length; i++) {
String part = s[i];
if (part.compareTo("Basic") == 0) {
String userPassBase64 = s[i + 1];
if (!userPassBase64.isEmpty()) {
String userPass = null;
try {
userPass = new String(DatatypeConverter.parseBase64Binary(userPassBase64));
} catch (RuntimeException e) {
throw new RuntimeException("Authorization cannot be decoded.", e);
}
String userPassArray[] = userPass.split(":");
if (userPassArray.length == 2) {
return userPassArray;
} else {
throw new RuntimeException("Invalid Authorization String.");
}
} else {
throw new RuntimeException("Invalid Authorization String.");
}
}
}
throw new RuntimeException("Authorization cannot be decoded.");
}
答案 2 :(得分:0)
我不知道手头的框架,但除非您使用BASIC身份验证,否则您可能无法获取该用户的密码。
如果您使用的是BASIC身份验证,Base64Decode
Authentication
标题会非常简单。