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:

<security-constraint>
      <web-resource-collection>
        <web-resource-name>
              REST calls
        </web-resource-name>
        <url-pattern>/*</url-pattern>
     </web-resource-collection>
      <auth-constraint>
          <role-name>ctispan</role-name>
      </auth-constraint>
  </security-constraint>
    <login-config>
      <auth-method>BASIC</auth-method>
      <realm-name>CTISpan REST</realm-name>
    </login-config>


tomcat-users.xml configuration:

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


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()");
    }

Copyright ©1993-2024 Joey E Whelan, All rights reserved.