Jetty 8中静态页面的基本HTTP身份验证

时间:2012-05-25 08:22:30

标签: java jetty

我的静态内容配置如下:

    ContextHandler staticContext = new ContextHandler();
    staticContext.setContextPath("/");
    staticContext.setResourceBase(".");
    staticContext.setClassLoader(Thread.currentThread().getContextClassLoader());

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[]{"index.html"});

    resourceHandler.setResourceBase(webDir);

    staticContext.setHandler(resourceHandler);

现在我想为所有静态文件设置Basic HTTP Auth。我怎么能这样做?

PS 即可。我正在使用嵌入式Jetty和web.xml

1 个答案:

答案 0 :(得分:3)

使用以下内容覆盖ResourceHandler#handle()

public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    String authHeader = request.getHeader("Authorization");

    if (authHeader != null && authHeader.startsWith("Basic ")) {
        String[] up = parseBasic(authHeader.substring(authHeader.indexOf(" ") + 1));
        String username = up[0];
        String password = up[1];
        if (authenticateUser(username, password)) {
            super.handle(target, baseRequest, request, response);
            return;
        }
    }

    response.setHeader("WWW-Authenticate", "BASIC realm=\"SecureFiles\"");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Please provide username and password");
}

private boolean authenticateUser(String username, String password) {
    // Perform authentication here
    return true; // .. if authentication is successful
}

private String[] parseBasic(String enc) {
    byte[] bytes = Base64.decodeBase64(enc.getBytes());
    String s = new String(bytes);
    int pos = s.indexOf( ":" );
    if( pos >= 0 )
        return new String[] { s.substring( 0, pos ), s.substring( pos + 1 ) };
    else
        return new String[] { s, null };
}

上面的Base64.decodeBase64来自Apache Commons Codec。当然,您可以找到一个为您执行Basic Auth的库,但在这里您可以看到幕后发生的事情。另一种方法可能是使用Basic Auth过滤器并将其安装到您的上下文中。