Create Secure Servlet using @ServletSecurity and HTTP Basic Authentication

[Updated: Jun 7, 2017, Created: Jan 22, 2016]

@ServletSecurity annotation is used to define access control constraints to servlets. The equivalent enforcement of security constraint via web.xml looks like this:

<web-app ...>






In above example we are securing AppController servlet access by supplying matching url pattern of <security-constraint>. That means requester has to provide valid username/password to access the resource. The security applies to only Get method. Also we are using BASIC authentication method specified in <login-config> element, which ends up browser specific standard login dialog. We are going to create equivalent annotation based servlet. Also we will use Tomcat for container managed security.

  1. Prepare project
    • Create web application using maven-archetype-webapp, steps here.
    • Here we are not going to delete web.xml as we still need to add <login-config> there.
    • In pom.xml add dependency of javax.servlet-api:3.0.1
    • In pom.xml add tomcat7-maven-plugin to run it as embedded server. Also note we have to provide tomcat-users.xml file. In standard installation of tomcat we can find that file under $CATALINA_BASE/conf/ folder.
    • We don't need any jsp or html file in this example so delete index.jsp created by default
  2. Create a servlet class AppController annotated with @WebServlet and @ServletSecurity
  3. Now we are going to run our web application from root folder:
    mvn clean tomcat7:run-war
  4. Put following url in your browser:
    You will see Authentication Required dialog (or similar dialog if using browser other than chrome v 47) Enter user name/password as provided in webapp/config/tomcat-users.xml. On successful login you should see the message printed by AppController servlet.

Example Project

Dependencies and Technologies Used:

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

Servlet Security Example Select All Download
  • web-servlet-security
    • src
      • main
        • java
          • com.logicbig.servlet
        • webapp
          • WEB-INF
          • config

See Also