By Alx: December 2017

Secure Jersey REST API with basic authentication


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




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 {

	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


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

public class StartRestServerWithAuthFilter {
	public static void main(String[] args) {
		HttpServer server;
		try {
			ResourceConfig config = new PackagesResourceConfig("");

			server = HttpServerFactory.create("http://localhost:10080/api", config);
		} 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=