Sunday, February 2, 2014

Jersey and OAuth

Introduction

Jersey contains support for the signing and verififcation of requests, per the OAuth Core 1.0 specification. There are three modules in the Jersey contributions section that provide support for OAuth:
  • OAuth signature library: provides core support for handling OAuth signatures
  • OAuth Jersey client filter: outgoing requests are automatically signed with OAuth signature
  • OAuth Jersey server request wrapper: wraps Jersey server requests to verify OAuth signature
For sample code, check out the oauth-tests in svn co https://svn.java.net/svn/jersey~svn/trunk contribs/jersey-oauth/oauth-tests

OAuth signature library

The OAuth signature library provides core support for generation, verification and signing of requests.
It supports the signature methods outlined in OAuth Core 1.0 specification: HMAC-SHA1, RSA-SHA1, and PLAINTEXT. Additional signature methods can be implemented by third parties and automatically loaded at the time the signature library JAR file is loaded.
Code that utilizes the OAuth signature library implement the OAuthRequest interface to expose the request to the library for signature generation/verification. Additionally, an OAuthParameters object contains the parameters used in signing, and OAuthSecrets object is used to specify the secrets that back the consumer key and/or access/request token. The OAuthSignature class is used to sign and verify requests.
Example usage:
// wrap an existing request with some concrete implementation
OAuthRequest request = new SomeConcreteOAuthRequestImplementation();
 
// establish the parameters that will be used to sign the request
OAuthParameters params = new OAuthParameters().consumerKey("dpf43f3p2l4k3l03").
 token("nnch734d00sl2jdk").signatureMethod(HMAC_SHA1.NAME).
 timestamp().nonce().version();
 
// establish the secrets that will be used to sign the request
OAuthSecrets secrets = new OAuthSecrets().consumerSecret("kd94hf93k423kf44").
 tokenSecret("pfkkdhi9sl3r4s00");
 
 // generate the digital signature and set in the request
 OAuthSignature.sign(request, params, secrets);

OAuth Jersey client filter

The OAuth Jersey client filter uses the OAuth signature library to automatically signs outgoing requests with established parameters and secrets. A filter instance can be added at one of two levels:
  • Client: all outgoing requests are signed with established parameters and secrets
  • WebResource: all requests to the resource are signed with established parameters and secrets
As WebResource objects are inexpensive to create, if the same resource must be signed with different parameters and/or secrets, new instances of the resource should be created to add a filter instance to.
The filter will not sign a request if an Authorization header is already present in the outgoing request. This allows previous filters in the chain to override behavior.
Example usage:
// baseline OAuth parameters for access to resource
OAuthParameters params = new OAuthParameters().signatureMethod("HMAC-SHA1").
consumerKey("key").setToken("accesskey").version();
 
// OAuth secrets to access resource
OAuthSecrets secrets = new OAuthSecrets().consumerSecret("secret").setTokenSecret("accesssecret");
 
// if parameters and secrets remain static, filter can be added to each web resource
OAuthClientFilter filter = new OAuthClientFilter(client.getProviders(), params, secrets);
 
// OAuth test server resource
WebResource resource = client.resource("http://term.ie/oauth/example/request_token.php");
 
// filter added at the web resource level
resource.addFilter(filter);
 
// make the request (signing it in the process)
String response = resource.get(String.class);
Notice in this example that timestamp and nonce are not explicitly set. When not set in the OAuthParameters object, the client will automatically set to the current time in seconds since epoch, and select a random nonce value. If a value is explicitly set, it is presumed to be intended to be sent in the request, and will not be overwritten.

OAuth Jersey server request wrapper

The OAuth Jersey server request wrapper uses the OAuth signature library to allow a Jersey server resource to manually verify the signature of an incoming request. It is a concrete implementation of the OAuthRequest interface in the OAuth signature library.
Example usage:
@GET
public String getVerified(@Context HttpContext hc) {
 
    // wrap incoming request for OAuth signature verification
    OAuthServerRequest request = new OAuthServerRequest(hc.getRequest());
 
    // get incoming OAuth parameters
    OAuthParameters params = new OAuthParameters();
    params.readRequest(request);
 
    OAuthSecrets secrets = new OAuthSecrets();
    ... set secrets based on consumer key and/or token in parameters ...
 
    try {
        return Boolean.toString(OAuthSignature.verify(request, params, secrets));
    }
    catch (OAuthSignatureException ose) {
        return "false";
    }
}
To comply with the OAuth protocol, this contrived example above should actually return a 400 or 401 status code in response rejecting the consumer request, depending on the reason of rejection.
Performing signature verification per-resource is generally discouraged; using a server filter method to verify incoming requests for groups of protected resources is far preferable. For example, the OpenSSO project has a working ServletFilter implementation in its OAuth extension that sets the user principal in the security context based on the OAuth signature. This allows JSPs and servlets to call the HttpServletRequest.getUserPrincipal method to determine the identity of the user that authorized the issuance of the access token.

Simple OAuth Authentication with a Container filter

Simple OAuth authentication for a servlet or filter may be set up using a Container Filter, which filters the request before the request is matched and dispatched to a root resource class. The Container Filter is registered usinginitialization parameters which point to a user defined class, such as the following:
public class OAuthAuthenticationFilter implements ContainerRequestFilter {
    @Override
    public ContainerRequest filter(ContainerRequest containerRequest) {
        // Read the OAuth parameters from the request
        OAuthServerRequest request = new OAuthServerRequest(containerRequest);
        OAuthParameters params = new OAuthParameters();
        params.readRequest(request);
        
        // Set the secret(s), against which we will verify the request
        OAuthSecrets secrets = new OAuthSecrets();
        // ... secret setting code ...
        
        // Check that the timestamp has not expired
        String timestampStr = params.getTimestamp();
        // ... timestamp checking code ...
        
        // Verify the signature
        try {
            if(!OAuthSignature.verify(request, params, secrets)) {
                throw new WebApplicationException(401);
            }
        } catch (OAuthSignatureException e) {
            throw new WebApplicationException(e, 401);
        }
        
        // Return the request
        return containerRequest;
    }
}

OAuth implementations using Jersey

  • OAuth4J is an OAuth implementation using Jersey.
Labels:

7 comments:

oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes

Anna said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

Best Recommended books for Spring framework

Java Interview Questions












Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai

Java Course in Chennai

Zheng junxai5 said...

zhengjx20160721
jordan 3 powder blue
coach outlet store online clearances
toms wedges
louis vuitton purses
coach outlet
cheap jordans
retro 11
oakley outlet
nike free 5.0
coach factory outlet
louis vuitton purses
gucci handbags
louis vuitton outlet online
adidas superstar trainers
louis vuitton handbags
coach outlet online
michael kors outlet
louis vuitton outlet
ralph lauren sale
michael kors purses
michael kors outlet
cheap toms shoes
nfl jerseys
cheap toms
ray ban sunglasses uk
louboutin femme
michael kors handbags
coach outlet store online
coach factory outlet
louis vuitton purses
nike sb dunks
nike blazers uk
coach outlet store
nike air max uk
nike uk
polo shirts
gucci bags
adidas running shoes
true religion outlet online
michael kors handbags

raybanoutlet001 said...

yeezy sneakers
basketball shoes
michael kors factory outlet
fitflops sale clearance
air jordan retro
links of london sale
cheap uggs
discount sunglasses
cheap nfl jerseys
true religion sale
michael kors handbags
http://www.raybanglasses.in.net
tiffany jewellery
ralph lauren polo shirts
nike dunks
tiffany online
oakley store online
oakley sunglasses,oakley outlet sunglasses
cheap real jordans
adidas nmd
ray ban uk,cheap ray ban sunglasses