Servlet - Triggering authentication programmatically with HttpServletRequest.authenticate()

[Updated: Jul 13, 2017, Created: Jul 13, 2017]

In this example, we will learn how to trigger container managed authentication programmatically by using HttpServletRequest.authenticate() method. In this case, we will not use @ServletSecurity (like last example) which is a declarative approach to specify security constraints on a servlet.


The Servlet

@WebServlet(name = "myServlet", urlPatterns = {"/"})
public class MyServlet extends HttpServlet {

  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {
      PrintWriter writer = resp.getWriter();

      if (shouldAuthenticate(req)) {
          boolean authenticated = req.authenticate(resp);
          if (authenticated) {
              if (req.getUserPrincipal() != null) {
                  writer.println("user authenticated " + req.getUserPrincipal().getName());
          } else {

      writer.println("<p>some data</p>");

  private boolean shouldAuthenticate(HttpServletRequest req) {
      //todo: apply some real condition
      return true;


Adding login-config in web.xml


<web-app xmlns=""
                   " version="3.1">



Adding tomcat-users.xml

As we are going to run embedded tomcat for this example, we will add tomcat-user.xml in the project:


<?xml version="1.0" encoding="UTF-8"?>
    <role rolename="employee"/>
    <user username="tina" password="123" roles="employee"/>

Specifying tomcat-user.xml location



To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war


On submitting user/password:

Example Project

Dependencies and Technologies Used :

  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

HttpServletRequest.authenticate() Example Select All Download
  • servlet-authenticate-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • WEB-INF
          • config

See Also