2009-10-19 110 views
0

我有一个要求在servlet应用程序中执行HTTP验证逻辑,而不是将此任务委托给容器。HTTP验证解码的开源Java服务器端实现

具体来说,我需要一种包含HTTP验证标头的HttpServletRequest的标头,并将它们解码为代表提供的凭证的数据结构,然后应用程序可以对其进行处理。基本和摘要认证都应该被支持。

我可以亲手写这篇文章,它不会太麻烦,RFC文档都很好,但我非常想用现成的库来为我做。我的第一个想法是Spring Security,但是从我可以告诉的是,这将这个任务委托给容器(我对此有点不清楚,它是一个复杂的代码库)。

任何人都知道其他人吗?

回答

2
  • 对于BASIC,实现起来非常简单 - 只需读取头文件,base64将其解码并将其拆分为':'字符。您也可以使用使用Spring的BasicProcessingFilter,并提供AuthenticationManager的实例。
  • 使用摘要,您无法从请求中获取密码(这就是整个问题......)。实施所有细节并不是一项简单的任务,即使认为该协议已有详细记录。所以我会选择Spring的DigestProcessingFilter。在这种情况下,您需要提供UserDetailsService谁提供基于用户名(用于摘要)的用户密码。
+0

非常好,那些过滤器正是我所需要的。谢谢。 – skaffman 2009-10-19 20:10:54

0

我不知道一个框架,但除非您使用BASIC身份验证,否则您可能无法获取该用户的密码。

如果您使用的是BASIC认证,那么Base64Decode标头的Authentication相当简单。

+0

这是简单的,是的,但不是小事,对报头中的格式要求是繁琐,而且容易出错。我不需要恢复明文密码,我只需要解码和编码头结构。 – skaffman 2009-10-19 15:48:43

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