Tuesday, November 19, 2013

Implementing HTTP Basic Auth with Java Jersey REST services

Server Side

Given we're using Jersey (a servlet) to implement the REST services, a logical place to implement HTTP Basic Auth would be at the servlet container level.  In this case - that's Apache Tomcat.  That can be easily implemented by adding configuration to two areas in Tomcat's config files:  web.xml and tomcat-users.xml

web.xml configuration:

              REST calls
      <realm-name>CTISpan REST</realm-name>

tomcat-users.xml configuration:

<role rolename="ctispan"/>
    <user username="client" password="password" roles="ctispan"/>

Note the relationship between the two files - specifically the "role-name" property.

Client Side

Implementing Basic Auth on the client side is a simple matter of adding the Jersey-provided Basic Auth filter to the client.

import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

private ClientRS(URI uri, String clientname, String clientpassword)
        logger.debug("Entering ClientRS(uri= " + uri +
                ", clientname= " + clientname +
                ", clientpassword= " + clientname + ")");
        ClientConfig config = new DefaultClientConfig();
        this.client = Client.create(config);
        if (clientname != null && clientpassword != null)
            this.client.addFilter(new HTTPBasicAuthFilter(clientname, clientpassword));
        this.service = this.client.resource(uri);
        logger.debug("Exiting ClientRS()");

No comments:

Post a Comment