This article continues the discussion started in the Servlet Authentication article. Here we discuss Form-Based authentication; another common form of authentication when Servlet technology is used.
Form-based Authentication, like Basic Authentication, requires the user to submit a userid and password. However, instead of relying upon the HTTP AUTHORIZATION header to propagate the security credentials, a Form-based login request implements a simple “work flow” based upon 302 redirects, a simple HTML form, and a POST operation to Servlet-spec defined Servlet that all Servlet Containers must implement.
Form-based Authentication uses a Servlet that is required to be available to all Web Applications. This doesn’t mean each WAR must have this Servlet class. The container must simply be able to process requests to this Servlet’s spec-defined path under each Context Root.
Figure 4 below shows the steps involved in accessing a page protected by JEE Security using Form-based Authentication. A Browser initially makes an HTTP GET call to index.html. The Server sees that the requested path is protected; it also sees that there is no existing security session that belongs to this request. So, the Server responds to the request with a 302 REDIRECT to a login page, login.jsp. What login page to display in this step is configurable in the WAR’s web.xml deployment descriptor. The login page must define a form similar to the following:
<form method="POST" action="j_security_check">
<td><input type="text" name="j_username"></td>
<td><input type="password" name="j_password"></td>
<td colspan=2 align=right><input type=submit value="Submit"></td>
Notice that this form will call POST on a path in the application’s context root called j_security_check. Also, notice that it has two form fields: j_username & j_password. The j_security_check Servlet is expecting a POST call that has these two fields defined. This call occurs when the Submit button is pressed. This HTML snippet will produce a web page that looks similar to the following:
Figure 4 — login.jsp Form Login page
The user must enter a username and password. Then, click Submit. This will cause the browser to submit an HTTP POST request with the username and password (in the form of a j_username & j_password field) to the j_security_check Servlet. The j_security_check Servlet intercepts this request, extracts the username and password, and attempts to authenticate the user. If the request is successful, the server will return an HTTP 302 Redirect that will send the user to the originally requested page. The browser will then, submit the original HTTP GET request for index.html, but this time it will include a security session identifier (usually in the form of a cookie) that will tell the container it has seen this user before.
Figure 5 — FORM – Based Authentication Sequence