Use cases for else with HttpServletRequest.authenticate in Java EE 6?

There are a few security methods added to javax.servlet.http.HttpServletRequest in Java Servlet 3.0 (part of Java EE 6) – login, logout and authenticate. Let’s focus on the latter – HttpServletRequest.html#authenticate(HttpServletResponse response).

Have a look at the following servlet and explain how it’s supposed to work and why.

package pl.japila.javaee6;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/authenticate")
public class AuthenticateServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean isAuthenticated = request.authenticate(response);
        System.err.println(">>> isAuthenticated: " + isAuthenticated);
        if (isAuthenticated) {
            request.getRequestDispatcher("/welcome.jsp").forward(request, response);
        } else {
            System.err.println(">>> ELSE: response has already been committed - no RequestDispatcher available. Why would I need it?!");
        }
    }
}

I’m mostly concerned with the else branch – why would I need it for? RequestDispatcher is not available and so no user interaction (as it’s already been initiated with authenticate and a user is supposed to enter credentials).

I wonder what the use cases could be to leverage the else branch? Anybody?

The deployment descriptor web.xml is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>AuthenticateWeb</display-name>
  <login-config>
    <auth-method>FORM</auth-method>
    <realm-name>DemoRealm</realm-name>
    <form-login-config>
      <form-login-page>/login.jsp</form-login-page>
      <form-error-page>/login.jsp?error=true</form-error-page>
    </form-login-config>
  </login-config>
  <error-page>
    <error-code>403</error-code>
    <location>/access-denied.jsp</location>
  </error-page>
</web-app>
Be Sociable, Share!
This entry was posted in Java EE, WebSphere.

Leave a Reply

%d bloggers like this: