Skip to content

Getting Started

Benton Porter edited this page Jul 8, 2014 · 4 revisions

On the Server

Add this maven dependency:

<dependency>
    <groupId>com.bazaarvoice.auth</groupId>
    <artifactId>jersey-hmac-auth-server</artifactId>
    <version>${version}</version>
</dependency>

Modify your Jersey resource methods to include a principal annotated with @HmacAuth. For example:

@Path("/pizza")
@Produces(MediaType.TEXT_PLAIN)
public class PizzaResource {
    @GET
    public String get(@HmacAuth Principal principal) {
        // This gets control only if the request is authenticated. 
        // The principal identifies the API caller (and can be of any type you want).    
    }
}

Implement an authenticator to authenticate requests and inject the @HmacAuth parameters:

public class MyAuthenticator extends AbstractCachingAuthenticator<Principal> {
    // some code is intentially missing 
    
    @Override
    protected Principal loadPrincipal(Credentials credentials) {
        // return the principal identified by the credentials from the API request
    } 

    @Override
    protected String getSecretKeyFromPrincipal(Principal principal) {
        // return the secret key for the given principal
    }
}

Register the authenticator with Jersey. For example, using Dropwizard:

environment.addProvider(new HmacAuthProvider(new DefaultRequestHandler(new MyAuthenticator())));

On the Client

On the client side, e.g. in an SDK library that interfaces with the API, the client must build requests following the authentication contract that jersey-hmac-auth implements. You can do this in any language. However, the jersey-hmac-auth library provides support in Java for client libraries that use the Jersey Client for making HTTP requests.

Add this maven dependency:

<dependency>
    <groupId>com.bazaarvoice.auth</groupId>
    <artifactId>jersey-hmac-auth-client</artifactId>
    <version>${version}</version>
</dependency>

Add this filter to your Jersey client (assuming you have already have a Jersey client instance):

client.addFilter(new HmacClientFilter(yourApiKey, yourSecretKey, client.getMessageBodyWorkers()));