Simple Basic Authentication from Java Servlet Example

Basic Auth is a very simple way to secure your web application. When combined with a secure transport technology like SSL, it’s also good enough in most cases.

Here is a dirt simple example of how to access the basic authentication information from the HTTP header in your servlet.

protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    String pathInfo = request.getPathInfo();
    //will contain "Basic Ym9iOnNlY3JldA=="
    String header = request.getHeader("Authorization"); 
    //always wise to assert your assumptions
    assert header.substring(0, 6).equals("Basic "); 
    //will contain "Ym9iOnNlY3JldA=="
    String basicAuthEncoded = header.substring(6);
    //will contain "bob:secret"
    String basicAuthAsString = new String(
        new Base64().decode(basicAuthEncoded.getBytes()));
    ...
}

You can test it with this curl command:

$  curl -vv http://bob:secret@localhost:8090/blah
* About to connect() to localhost port 8090 (#0)
*   Trying ::1... connected
* Connected to localhost (::1) port 8090 (#0)
* Server auth using Basic with user 'bob'
 GET /blah HTTP/1.1
 Authorization: Basic Ym9iOnNlY3JldA==
 User-Agent: curl/7.19.4 (universal-apple-darwin10.0) libcurl/7.19.4 OpenSSL/0.9.8k zlib/1.2.3
 Host: localhost:8090
 Accept: */*
...