JAAS-based security authentication on servlet

The JAAS-based security authentication on servlet is an extension of JAAS-based security authentication for JSPs. In this section, we are demonstrating that we can even apply security on servlets.

Getting ready

  • Create a new Web Project in Eclipse
  • Create a package, com.packt.security.servlets
  • Create a Servlet with name ProtectedServlets

How to do it...

The following are the steps for JAAS-based security for servlet:

  1. Create a servlet and name it ProtectedServlets:
    public class ProtectedServlets extends HttpServlet {
      private static final long serialVersionUID = 1L;
        
      public ProtectedServlets() {
        super();
           
      }
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        try
        {
          out.println("Hello User");
          out.println("Authtype:"+request.getAuthType());
          out.println("User Principal:"+request.getUserPrincipal());
          out.println("User role:"+request.isUserInRole("role1"));
        }
        catch (Exception e) {
          out.println("<b><font color='red'>failed authenticatation</font>-</b>"+e);
    
        }
      }
    
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
      }
    
    }
  2. Now, edit the web.xml file to secure the servlet:
    <web-resource-collection>
    <web-resource-name>Servlet Protection</web-resource-name>
    <description>Declarative security tests</description>
    <url-pattern>/ProtectedServlets</url-pattern>
    <http-method>HEAD</http-method>
    <http-method>GET</http-method>
    <http-method>POST</http-method>
    <http-method>PUT</http-method>
    <http-method>DELETE</http-method>
    </web-resource-collection>

How it works...

Restart the server and access the URL: http://localhost:8080/jaas-jboss/ProtectedServlets.

You would get a login form, which will authenticate the user. The servlet is the protected resource, and anyone accessing the servlet will be asked to log in. The authentication is handled by JAAS API, which is application-server-specific. Each application server will have its own implementation of security.

See also

  • The Container-based basic authentication on servlet recipe
  • The Form-based authentication on servlet recipe
  • The Form-based authentication with open LDAP and servlet recipe
  • The Hashing/Digest Authentication on servlet recipe
  • The Basic authentication for JAX-WS and JAX-RS recipe
  • The Enabling and disabling the file listing recipe