Building the OAuth 1.0 client using Jersey APIs

Let's build a simple client to understand the API usage for accessing the OAuth 1.0 protected resource. Note that the JAX-RS specification does not have standardized APIs for the OAuth client yet. This example uses the Jersey API to build the OAuth 1.0 client.

The complete source code for this example is available on the Packt website. You can download the example from the Packt website link that is mentioned at the beginning of this book, in the Preface section. In the downloaded source code, see the rest-chapter6-oauth1-client project.

You should start by specifying the dependency to the oauth1-client JAR file in the client application. If you use Maven to build the client, the dependency entry in pom.xml may look as follows:

<dependency> 
    <groupId>org.glassfish.jersey.security</groupId> 
    <artifactId>oauth1-client</artifactId> 
    <!-- specify appropriate version(2.26-b09) --> 
    <version>${jersey.version}</version> 
</dependency> 

Here are the detailed steps for accessing the OAuth 1.0 protected resource:

  1. OAuth 1.0 includes a consumer key and a matching consumer secret that together authenticate the client application to the service provider. You may want to obtain these credentials from the respective service provider for use in the client code. The org.glassfish.jersey.client.oauth1.OAuth1ClientSupport class is the starter class to build the support for OAuth 1.0 into the Jersey client. The OAuth1Builder object obtained from OAuth1ClientSupport can be used to build OAuth1AuthorizationFlow by calling the authorizationFlow() method. The authorizationFlow() method takes the following endpoints (these values can be obtained from the service provider):
    • Request token URI: This is the URI of the endpoint on the authorization server, where the request token can be obtained
    • Access token URI: This is the URI of the endpoint on the authorization server, where the access token can be obtained
    • Authorization URI: This is the URI of the endpoint on the authorization server to which the user (the resource owner) should be redirected in order to grant access to this application (our consumer)
  1. The following code snippet illustrates the previously discussed step. This example tries to access the Twitter API protected with OAuth 1.0:
//Other imports are not shown for brevity 
import javax.ws.rs.client.Client; 
import javax.ws.rs.client.ClientBuilder; 
import javax.ws.rs.core.Feature; 
import org.glassfish.jersey.client.oauth1.ConsumerCredentials; 
import org.glassfish.jersey.client.oauth1.OAuth1AuthorizationFlow; 
import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport; 
 
// Read consumer key/secret from API provider 
// You should obtain these keys from appropriate 
// service provider (e.g. Twitter) 
final String CONSUMER_KEY = "xxxxxxxx"; 
final String CONSUMER_SECRET =  "xxxxxxx"; 
// ConsumerCredentials stores client secret as  
// byte array to improve security. 
final ConsumerCredentials consumerCredentials = new  
   ConsumerCredentials( CONSUMER_KEY,  CONSUMER_SECRET); 
//Build the OAuth1AuthorizationFlow by supplying URI for 
//reading request token, access token and authorize token 
//This client reads Tweets on behalf of the end user   
final OAuth1AuthorizationFlow oauth1AuthoriznFlow =  
   OAuth1ClientSupport.builder(consumerCredentials) 
      .authorizationFlow(    
           "https://api.twitter.com/oauth/request_token", 
           "https://api.twitter.com/oauth/access_token", 
           "https://api.twitter.com/oauth/authorize") 
           .build(); 
  1. Once you have the org.glassfish.jersey.client.oauth1.OAuth1AuthorizationFlow instance ready, you can kick off the authorization process. To start the authorization process, call the start() method on the OAuth1AuthorizationFlow instance. Under the cover, the start() method makes a request to the request token URI and gets the request token that will be used for the authorization process. The method returns the authorization URI as a string:
//Get authorization URI 
String authorizationUri = oauth1AuthoriznFlow 
    .start(); 
  1. The next step in the authorization flow is to redirect the user to the authorization URI returned by the start() method. If the client is a web application, you can use servlet APIs or JAX-RS APIs to implement the redirection.
  2. After successful authorization, the authorization server redirects the user back to the URI specified by OAuth1Builder.FlowBuilder::callbackUri(String) and also provides oauth_verifier as a query parameter in the callback URI. The client should extract this parameter from the request and finish the authorization flow by calling the finish(verifier) method. The finish() method will internally request the access token from the authorization server and return it:
//Get the access token and finish the authorization flow  
AccessToken accessToken = oauth1AuthoriznFlow.finish(verifier); 
OAuth 1.0 works by ensuring that both the client and server share an OAuth token and a consumer secret. The client must generate a signature on every request (or REST API call) by encrypting a bunch of unique information using the consumer secret. The server must generate the same signature, and only grant access if both the signatures match.
  1. The OAuth client application used in this example will use the access token obtained from the AccessToken instance together with the client secret from the org.glassfish.jersey.client.oauth1.ConsumerCredentials object to perform OAuth-authenticated requests to the service provider. Remember that we have created the ConsumerCredentials instance at the beginning of this example as a part of the OAuth1AuthorizationFlow initialization by passing the consumer key and secret.
  2. The OAuth1 filter feature obtained by calling getOAuth1Feature() on the OAuth1AuthorizationFlow object can be used to configure client instances to perform authenticated requests to the server. This filter feature will prepare all the requests from the client compatible to OAuth 1.0. The following code snippet illustrates the use of the OAuth filter feature to access the protected resources from the service provider:
//See the code snippet at the beginning of this section 
//to know how we created oauth1AuthoriznFlow object 
Feature filterFeature = oauth1AuthoriznFlow.getOAuth1Feature(); 
//create a new Jersey client and register filter  
//feature that will add OAuth signatures and  access token 
Client client = ClientBuilder.newBuilder() 
          .register(filterFeature) 
          .build(); 
 
// Protected REST API URI that application wants to access:  
//https://<service-provider>/<resource>" 
//This example access following twitter API 
final String PROTECTED_RESOURCE_URI = 
    "https://api.twitter.com/1.1/statuses/home_timeline.json";  
 
  // make requests to protected resources 
  final Response response =  
         client.target(PROTECTED_RESOURCE_URI).request().get(); 
  if (response.getStatus() != 200) { 
    String errorEntity = null; 
    if (response.hasEntity()) { 
      errorEntity = response.readEntity(String.class); 
    } 
    throw new RuntimeException( 
         "Request to protected resource was not successful"); 
  }else{ 
      //Code for processing the response goes here 
       String result = response.readEntity(String.class); 
   } 

After having understood the OAuth 1.0 protocol and its usage, let's move on to the OAuth 2.0 protocol. The next section discusses this topic in detail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.190.175