Skip to main content

Jersey Java Framework - How to add HTTP Basic Authentication to RESTful web services?


Overview


I have shown you in the following post how to develop the RESTful web services using the Jersey Java Framework

Jersey JAX-RS Framework - Step by Step Guide for Developing RESTful web services

There are different security levels that we can add to web services

  • a) Authentication
  • b) Authorization
  • c) Encryption


The scope of this post is for Authentication. If we look at the available options then we have

  • a) OpenID
  • b) OAuth
  • c) HTTP Basic Authentication 


HTTP Basic level authentication is the weakest among the above three available options but it is still preferable over no Authentication :)

Let's start how to implement the Basic HTTP Authentication.

Requirements for this tutorial
  •  Eclipse
  •  Maven
  • Jersey Framework
  • Tomcat

STEP 1

First, we will code our filter to process the request before redirecting it to the respective resource. We will achieve it by implementing the ContainerRequestFilter. We will add the following dependency to the maven

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>3.0-alpha-1</version>
    <scope>provided</scope>
</dependency>


STEP 2

package com.techieshah.filters;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response.Status;
import javax.xml.bind.DatatypeConverter;

/**
 * @author techieshah.blogspot.com
 *
 */
public class HTTPBasicAuthenticationFilter implements ContainerRequestFilter{

@Context
HttpServletRequest httpServletRequest;

public void filter(ContainerRequestContext containerRequest) throws IOException {
final String AUTHENTICATION_HEADER = "Authorization";
String auth = containerRequest
.getHeaderString(AUTHENTICATION_HEADER);
     
        if(auth == null){
        throw new WebApplicationException(Status.UNAUTHORIZED);
        }   
     
        String lap[] = decode(auth);     
     
      //If login or password fail
        if(lap == null || lap.length < 2){
            throw new WebApplicationException(Status.UNAUTHORIZED);
        }
     
        if( ! ( "testUser".equals( lap[0] ) || "test01".equals( lap[1] ) ) ){
        throw new WebApplicationException(Status.UNAUTHORIZED);
        }
}

private String[] decode(String auth) {
        //Replacing "Basic THE_BASE_64" to "THE_BASE_64" directly
        auth = auth.replaceFirst("[B|b]asic ", "");
        byte[] bytes = DatatypeConverter.parseBase64Binary(auth);
     
        if(bytes == null || bytes.length == 0){
            return null;
        }
        return new String(bytes).split(":",2);           
    }
}


In the above code, we have overridden the filter method in order to look for authentication credentials.

STEP 3 

In the last step, we will add the above filter in the init-param to the web.xml file

     <init-param>
         <param-name>jersey.config.server.provider.classnames</param-name>
         <param-value>com.techieshah.filters.HTTPBasicAuthenticationFilter;</param-value>
     </init-param> 


403 Unauthorized status code in response will be returned if Basic Authentication header is missing OR wrong credentials are provided.

Source code for this tutorial can be found on the github address i.e. JerseyHTTPBasicAuthentication

Comments

Popular posts from this blog

Eclipse - Server Tomcat v8.5 Server at localhost failed to start.

When I try to launch the tomcat from Eclipse, I encountered the following error Server Tomcat v8.5 Server at localhost failed to start. Solution Step 1  Delete the .snap file located at the following location     eclipse workspace Path\ .metadata\.plugins\org.eclipse.core.resources Step 2 Delete the  tmp0  folder from the following path      eclipse workspace Path \.metadata\.plugins\org.eclipse.wst.server.core Step 3  Delete the server from servers list Step 4  Remove already added Tomcat Server      i)  Click on Define a new Server     ii)  Select Server Runtime Environments     iii) Select the Tomcat Server and remove it as follows Remove Selected Server Step 5 Make sure that correct version of Server is configured in Project Properties Step 6 Restart the Eclipse IDE.

Intellij : How to add @author comment to every new class

 Introduction In this tutorial, we will learn how to add @author comments to every new class that we create. We can achieve it using either of the following two solutions Solution 1:  Automatically add @author comments to every new class using Files and Code Templates Open File -> Settings -> Editor -> File and Code Templates -> Includes Click on Includes . Under File Header , enter the following comments text /**  * @author ${USER}  * @Date ${DATE}   */ Intellij - add @author comments Solution 2: Autocompletion of @author Open File  ->  Settings  ->  Editor  -> Live Templates Select Java and then click on + button In Abbreviation, enter @a In template text , enter the following comments           /**             * @author ${USER}             * @Date ${DATE}            */ In option , Expands with select SPACE Intellij - Autocompletion @author You can simply add the @author comments by typing @a and then click SPACE

hibernate-release-5.4.4.Final - Required Jars

Introduction Hibernate (Object Relational Mapping framework) is an implementation of Java Persistence API (JPA) specification.   Required Jars for Hibernate 5.4.4 Following Jars resided inside the required folder are the mandatory jars required for Hibernate 5.4.4 antlr-2.7.7.jar byte-buddy-1.9.11.jar classmate-1.3.4.jar dom4j-2.1.1.jar FastInfoset-1.2.15.jar hibernate-commons-annotations-5.1.0.Final.jar hibernate-core-5.4.4.Final.jar istack-commons-runtime-3.0.7.jar jandex-2.0.5.Final.jar javassist-3.24.0-GA.jar javax.activation-api-1.2.0.jar javax.persistence-api-2.2.jar jaxb-api-2.3.1.jar jaxb-runtime-2.3.1.jar jboss-logging-3.3.2.Final.jar jboss-transaction-api_1.2_spec-1.1.1.Final.jar stax-ex-1.8.jar txw2-2.3.1.jar Hibernate 5.4.4 release is compatible with  Java 8 or 11  JPA 2.2 References https://hibernate.org/orm/releases/5.4/