Secure Jersey 2 Hello World Example

Secure Jersey 2 Hello World Example

Jersey is very popular framework to build restful services. In this tutorial, we will learn how to do HTTP basic authentication, so that user won’t be able to access any resource untill they provided the correct username and passowrd. This example has been extended from our previous simple Jersy 2 Hello World tutorial. Please refer the previous tutorial for technology used and basic configurations.

Step1: Intercept the request

Add below servlet configuration in your web.xml file –

We have added a servlet filter class RestAuthenticationFilter for all urls of the form /rest/*.

Step 2: RestAuthenticationFilter class

This is basic class to get the HTTP Header value for Authorization.

Step 3: AuthenticationService

This class is used to authenticate the username and password to verify the user.

Step 5: HelloJerset class

Step 6: Run the application

Run the application on any of web application server, I have used tomcat 7 and hit http://localhost:8080/RestExample/rest/hello using Postman a Chrome extension to test the RESTful services.

Hit the above url without any username and password –


We can see, it gives an error 401 Unauthorized which is highlighted in above snapshot

Now add the username and passowrd in the request and again hit the url –

Select Basic Auth from Type drop down, provide the username & password and click on Update Request. Now click on Send button and get the result.



Download the sample code – RestExample

Stay tuned with us for more tutorials!

Happy Learning!!!


Leave a Reply

Your email address will not be published. Required fields are marked *