HTTP身份验证解码的开源Java服务器端实现

时间:2009-10-19 15:04:28

标签: java servlets http-authentication

我需要在servlet应用程序中执行HTTP身份验证逻辑,而不是将此任务委派给容器。

具体来说,我需要一种方法来获取包含HTTP身份验证头的HttpServletRequest的标头,并将它们解码为表示所提供凭据的数据结构,然后应用程序可以处理该凭据。应支持基本身份验证和摘要身份验证。

我可以手工编写,这不是太多的苦差事,RFC都有很好的文档记录,但我非常想使用现成的库为我做这件事。

我的第一个想法是Spring Security,但是我可以告诉他将此任务委托给容器(我有点不清楚,这是一个复杂的代码库)。

任何人都知道其他人吗?

3 个答案:

答案 0 :(得分:2)

  • 对于BASIC,它很容易实现 - 只需读取标题,base64解码它并将其拆分为':'字符。您也可以使用Spring的BasicProcessingFilter,并提供AuthenticationManager的实例。
  • 使用Digest,您无法从请求中获取密码(这就是重点......)。实现所有细节并不是一项微不足道的任务,甚至认为协议已有详细记录。因此,我会选择Spring DigestProcessingFilter。在这种情况下,您需要提供基于用户名(用于摘要)提供用户密码的UserDetailsService

答案 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标题会非常简单。