在servlet中实现HTTP基本身份验证

时间:2013-03-25 09:37:29

标签: java servlets http-basic-authentication

我想编写一个包含一组资源的servlet,需要使用基本的HTTP身份验证来保护它们;在提供文件之前,将针对后端数据库检查提交的用户名/密码。

有没有人有这方面的工作实例?我在http://www.coderanch.com/t/352345/Servlets/java/HTTP-basic-authentication-Web-Applications尝试了该示例,但它在IllegalStateException来电中一直返回sendError

1 个答案:

答案 0 :(得分:19)

这是一些返回Credential对象的代码(持有登录名和密码的bean对象)。

public Credentials credentialsWithBasicAuthentication(HttpServletRequest req) {
    String authHeader = req.getHeader("Authorization");
    if (authHeader != null) {
        StringTokenizer st = new StringTokenizer(authHeader);
        if (st.hasMoreTokens()) {
            String basic = st.nextToken();

            if (basic.equalsIgnoreCase("Basic")) {
                try {
                    String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
                    LOG.debug("Credentials: " + credentials);
                    int p = credentials.indexOf(":");
                    if (p != -1) {
                        String login = credentials.substring(0, p).trim();
                        String password = credentials.substring(p + 1).trim();

                        return new Credentials(login, password);
                    } else {
                        LOG.error("Invalid authentication token");
                    }
                } catch (UnsupportedEncodingException e) {
                    LOG.warn("Couldn't retrieve authentication", e);
                }
            }
        }
    }

    return null;
}

效果很好,即使密码如下:& = /?é$£。

这是使用jMock:

的类的基本单元测试
public void testCredentialsWithBasicAuthentication() {
    // Setup
    final HttpServletRequest request = context.mock(HttpServletRequest.class);

    AuthentificationHelper helper = new AuthentificationHelper();
    String login = "mickael";
    String password = ":&=/?é$£";
    String base64Hash = Base64.encodeString(login + ":" + password);
    final String authHeader = "Basic " + base64Hash;

    // Expectations
    context.checking(new Expectations() {
        {
            oneOf (request).getHeader("Authorization");
            will(returnValue(authHeader));
        }   
    });

    // Execute
    Credentials credentials = helper.credentialsWithBasicAuthentication(request);

    // Verify
    assertNotNull(credentials);
    assertEquals(login, credentials.getLogin());
    assertEquals(password, credentials.getPassword());

    context.assertIsSatisfied();
}