0

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

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

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

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

有人知道其他人吗?

4

3 回答 3

2
于 2009-10-19T16:20:59.620 回答
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.");
}
于 2012-07-30T23:25:01.220 回答
0

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

如果您使用的是 BASIC 身份验证,则对标头来说非常Base64Decode简单Authentication

于 2009-10-19T15:45:10.927 回答