skayred
skayred

Reputation: 10713

Basic HTTP Auth for static pages in Jetty 8

I have static content configured like this:

    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);

And now I want to set Basic HTTP Auth for all my static files. How can I do this?

PS. I'm using embedded Jetty withour web.xml

Upvotes: 1

Views: 1126

Answers (1)

Edvin Syse
Edvin Syse

Reputation: 7297

Override ResourceHandler#handle() with something like:

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 };
}

The Base64.decodeBase64 above is from Apache Commons Codec. Of course you can find a library that does Basic Auth for you, but here you can see what happens under the covers. Another approach could be to use a Basic Auth filter and install that into your context.

Upvotes: 3

Related Questions