Http Basic Authentication

Here’s a brief overview of Http Basic Authentication which is a (trivial) way of providing authentication in your application. Every-time you send a http request to the server, the username and password are sent as part of the HTTP header (in every request). They are encoded using base64, so yes it is NOT a safe way to do things. If you decide to use it, make sure you use SSL over it.

  1. Users sends a request.
  2. Server sends back response code 401 and Http response header WWW-Authenticate = Basic realm=”MyRealm”. Browser receives this (header and response code) and prompts user to enter username and password.
  3. Browser sends another GET request but with Http request header Authorization: Basic .
  4. Server receives this header, authenticates the user and sends back either a Response code 200 (OK) or 401 (Unauthorized).

If the response is 200 (Ok) browser will cache the username and password so that user doesn’t have to keep reentering it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
 
public class AuthenticateServlet extends HttpServlet {
 
  private static final long serialVersionUID = 1L;
 
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
    if ( request.getHeader("Authorization") != null ) {
      String auth = request.getHeader("Authorization");
      String coded_user_password = auth.split(" ") [1];
      String decoded_user_password = StringUtils.newStringUtf8(Base64.decodeBase64(coded_user_password));
 
      String username = decoded_user_password.split(":")[0];
      String password = decoded_user_password.split(":")[1];
 
      PrintWriter out = response.getWriter();
      out.println("<p>Username: " + username + "</p><p>Password: " + password + "</p>");
 
    } else {
 
      response.setHeader("WWW-Authenticate", "Basic realm=\"MyRealm\"");
      response.setStatus(401);
 
    }
  }
}