繁体   English   中英

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

[英]Open-source Java server-side implementations of HTTP auth decoding

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

具体来说,我需要一种方法来获取包含HTTP auth头的HttpServletRequest头,并将其解码为表示提供的凭据的数据结构,然后由应用程序进行处理。 基本身份验证和摘要身份验证均应受支持。

我可以手工编写,这不会太麻烦,RFC都有详细的文档记录,但是我很想使用现成的库为我做。

我的第一个想法是Spring Security,但是据我所知,这可以将任务委托给容器(对此我不太清楚,这是一个复杂的代码库)。

有人认识吗?

  • 对于BASIC,很容易实现-只需读取标头,对base64进行解码,然后将其分割为':'字符即可。 您还可以使用use Spring的BasicProcessingFilter ,并提供AuthenticationManager的实例。
  • 使用摘要,您无法从请求中获取密码(这很重要...)。 实现所有细节并不是一件容易的事,即使该协议有充分的文档证明。 因此,我将使用Spring的DigestProcessingFilter 在这种情况下,您需要提供UserDetailsS​​ervice ,后者将根据用户名(摘要)提供用户密码。

这是我的解码器:

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.");
}

我不了解现有的框架,但是除非您使用BASIC身份验证,否则您可能无法获取用户密码。

如果您使用的是BASIC身份验证,那么对Base64Decode Authentication标头来说,这很简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM