By Alx: December 2017

Secure Jersey REST API with basic authentication

Goal

In a previous post rest hello world i demonstrated how to create a simple rest api, now i will show you how to secure this API with basic authentication

AuthenticationFilter

package com.wstutorial.rest.filter;

import javax.ws.rs.WebApplicationException;

import com.sun.jersey.api.client.ClientResponse.Status;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;

public class AuthenticationFilter implements ContainerRequestFilter {

	@Override
	public ContainerRequest filter(ContainerRequest containerRequest)
			throws WebApplicationException {
		String httpMehod = containerRequest.getMethod();
		String path = containerRequest.getPath();

		// Allow GET wadl
		if (httpMehod.equals("GET") && path.contains("wadl")) {
			return containerRequest;
		}

		String auth = containerRequest.getHeaderValue("authorization");

		// Return 401 if authorization header is missing
		if (auth == null) {
			throw new WebApplicationException(Status.UNAUTHORIZED.getStatusCode());
		}

		boolean isAuthenticated = checkAuthentication(auth);

		return isAuthenticated == true ? containerRequest : null;
	}

	// For simplicity it checks only if auth contains "basic"
	private boolean checkAuthentication(String auth) {
		return auth.toLowerCase().contains("basic");
	}
}

Rest Starter

package com.wstutorial.rest;

import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.net.httpserver.HttpServer;

public class StartRestServerWithAuthFilter {
	public static void main(String[] args) {
		HttpServer server;
		try {
			
			ResourceConfig config = new PackagesResourceConfig("");
			config.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, 
					"com.wstutorial.rest.filter.AuthenticationFilter");

			server = HttpServerFactory.create("http://localhost:10080/api", config);
			server.start();
		} catch (Exception e) {
			System.out.println("Errormessage : " + e.getMessage());
		}

	}
}

Test with curl

// wadl is accessible without any restriction
curl -i http://localhost:10080/api/application.wadl
HTTP/1.1 200 OK

curl -i http://localhost:10080/api/hello
HTTP/1.1 401 Unauthorized

curl -H 'Authorization: Basic dGVzdDpzZWNyZXQ=' http://localhost:10080/api/hello
hello World!
This command pass the Authorization header. This header look like Authorization: <scheme> <credentials>
Scheme is basic and credentials are base64-encoded
test:secret is equivalent to dGVzdDpzZWNyZXQ=

References