1

我的静态内容配置如下:

    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。我怎样才能做到这一点?

附言。我正在使用带有 web.xml 的嵌入式 Jetty

4

1 回答 1

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。当然,您可以找到一个为您执行基本身份验证的库,但在这里您可以看到幕后发生的事情。另一种方法可能是使用基本身份验证过滤器并将其安装到您的上下文中。

于 2012-06-07T19:15:42.203 回答