Wednesday 1 October 2014

How to Secure RESTful Webservice in Jersey and Tomcat

This example explain how to make JAX-RS resource secured using HTTP Basic Auth.

I will enable HTTP Basic Authentication for the RESTful Webservice created in my previous blog Creating Jersey Restful Webservice.

Secure Resource With web.xml

You need to define the <security-constraint> elements in the web.xml and assign roles which are able to access these resources.


  <security-constraint>
    <web-resource-collection>
      <web-resource-name>BasicSecurityExample</web-resource-name>
      <url-pattern>/webapi/myresource</url-pattern>
      <http-method>GET</http-method>
    </web-resource-collection>
    <auth-constraint>
      <description>Authorized role is admin</description>
      <role-name>MyRole</role-name>
    </auth-constraint>
  </security-constraint>
  <login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>Login</realm-name>
   </login-config>

To Secure multiple resources we have to add <security-constraint> for each resource we need to securr or we can secure multiple resource using wildcard in <url-pattern> like below.


  <security-constraint>
    <web-resource-collection>
      <web-resource-name>BasicSecurityExample</web-resource-name>
      <url-pattern>/webapi/*</url-pattern>
      <http-method>GET</http-method>
    </web-resource-collection>
    <auth-constraint>
      <description>Authorized role is admin</description>
      <role-name>MyRole</role-name>
    </auth-constraint>
  </security-constraint>

Create User in Tomcat Server.


In Tomcat we can add user in tomcat-users.xml file which is located in <TOMCAT_HOME>/conf folder. Add the below entry in tomcat-user.xml file to add a User test with Password test with role as MyRole.


<user password="test" roles="MyRole" username="test"/>


Now our GET method in the resource /webapi/myresource is secure. Run the application.

Open any browser and go to the below link http://localhost:8080/FirstDemo/
You will See the index page for the application.
Click on the Jersey resource to access the Jesery REST service.
When we click on the link we will be asked for Username and Password to login. GIve username and password as test to access the resource.


This post explains about enabling security in web.xml  without touching the java code.In my next blog i will share how to enable security via annoatation in java code.

No comments:

Post a Comment