Security REST service using web.xml

In the Using JPA in REST web application deployed in Jetty entry i talked about how to create a REST service which uses JPA to interact with database. This service allows you to list, insert, update and delete records from CONTACT table. When you create a service that allows you to update your back end you might want to protect it so that only authorized user can update the database. I wanted to figure out how to protect the service so that every user can get list of contacts but only ADMIN user is able to modify the contacts by inserting, updating and deleting them. YOu can download the sample application that i developed from here When the user tries to insert a new record he will get prompted for basic authentication like this I followed these steps to build the sample application
  1. First i did download the basic that provides REST interface and i tested it to make sure that it works
  2. Next i used the instructions in Securing web application deployed in Jetty to make changes in Maven build file(pom.xml) to enable loginService in Jetty
              <loginService implementation="">
              <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
  3. Next create file in ${basedir}/src/main/resources directory which looks like this
    This file has only 2 users first is guest and second is admin the admin user has ADMIN role.
  4. The next step is to make changes in web.xml to protect the appropriate HTTP method calls in web.xml like this
    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "" >
      <display-name>Archetype Created Web Application</display-name>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-name>Jersey Web Application</servlet-name>
          <web-resource-name>Create Contact</web-resource-name>
    The most important change in web.xml is defining the security constraints for the /rest URL, which is the base URL for the REST service. The security constraint says that only allow those users who have ADMIN role access to POST, PUT, DELETE HTTP methods on this URL. The login-config element says that use Basic authentication
Now run the web application by executing mvn jetty:run and you will notice that you can get list of contacts but when you try to either insert a new contact or delete existing contact then you will get prompted for userid and password

No comments: