Two-Legged Versus Three-Legged OAuth

We’ve already explored the standard, three-legged (application, provider, user) method for using OAuth 1.0a, stepping through the token-exchange workflow to gain an access token. Although this is how OAuth was originally intended to be used, some providers employ another method, two-legged OAuth, to allow application developers to collect private data with aggregated sources such as firehose feeds.

The implementation of two-legged OAuth mimics typical client-server communication relationships and removes the need to involve users in the process. This is a good way for providers to allow applications to access data on their systems while being able to track the amount of data that the application is requesting, mostly for rate-limiting and abuse-prevention purposes.

Note

A good way to think about two-legged OAuth is as the first and last steps of the three-legged OAuth process (getting the request token and exchanging that for an access token), eliminating the middle pieces in which the user authorizes the application.

The workflow for the two-legged OAuth process is:

  1. The application owner creates a new OAuth application on the provider site to obtain a consumer key and secret.

  2. The application will make requests to the provider site to access private data.

This process is much easier, but doesn’t fulfill the need for an intermediary user authorization step when you’re requesting privileged user information.

Now let’s take a look at a practical example of the two-legged OAuth scenario.

Implementing two-legged OAuth in JavaScript

Let’s see what a two-legged OAuth example looks like when being used to make an actual request to a provider site. There are a few things that I need to spell out about this example before we begin:

  • We will be making a request through the Yahoo! Query Language (YQL) service to access a firehose feed from the Yahoo! update stream. These updates will contain notifications of any and all actions that are taken on the sites or services around Yahoo!.

  • We will need to create an OAuth application through the Yahoo! Developer Network dashboard at http://developer.yahoo.com/dashboard to obtain our OAuth consumer key and consumer secret to sign the request.

  • We will be making our cross-domain AJAX request using JQuery.

Warning

There are not many end-to-end samples available in JavaScript because of the security issues behind embedding your OAuth keys in the JavaScript layer. Be aware that if you employ a JavaScript implementation, you’ll need to protect your keys to prevent others from using them without your knowledge.

With those preliminaries out of the way, let’s jump right into this short example.

The includes

The first thing to do, besides setting up the top of the HTML document, is specify the following includes:

oauth.js

The OAuth library for generating our signature

sha1.js

The signing library

jquery.min.js

The minified JQuery base object

This will be the base of our example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>OAuth JavaScript Sample Application</title>
</head>
<body>

<!-- OAuth libraries and JQuery base -->
<script src="http://oauth.googlecode.com/svn/code/javascript/oauth.js"></script>
<script src="http://oauth.googlecode.com/svn/code/javascript/sha1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>

Next let’s look at the function that will generate the OAuth request URI.

Constructing the OAuth request URI

The function to generate the OAuth request URI will accept three parameters: the OAuth consumer key and secret, and the URI endpoint to which we will make our two-legged OAuth requests. We will use those parameters to build a signed URL request:

<script type="text/javascript">
/*******************************************************************************
 * Function: Build OAuth Request
 * Description: Builds a 2-legged OAuth signed request URI using a given OAuth
 *           key and secret with a specified URI endpoint
 ******************************************************************************/
var buildOAuthRequest = function(key, secret, url){
   //create accessor and message objects
   var accessor = { consumerSecret:secret, tokenSecret:"" };
   var message = { action:url, method:"GET",
                   parameters:[["oauth_version", "1.0"],
                              ["oauth_consumer_key", key]]};

   //set timestamp, nonce and signature method
   OAuth.setTimestampAndNonce(message);
   OAuth.SignatureMethod.sign(message, accessor);

   //build signature URL
   var baseString =
      OAuth.decodeForm(OAuth.SignatureMethod.getBaseString(message));
   var signature =
      OAuth.getParameter(message.parameters, "oauth_signature");
   var signatureURL = baseString[1][0] + "?" + baseString[2][0]
                    + "&oauth_signature=" + encodeURIComponent(signature);

   return signatureURL;
};

We start by creating two objects to build the request. The first is an accessor object that will contain the consumer secret from the OAuth application and a blank token secret value. The second is the message object that acts as our request object and contains the URI endpoint to which we’re making a request, the method type, and the OAuth consumer key and version as parameters.

Once we’ve created these objects, we generate a new OAuth timestamp and nonce using the message, and then sign the message using the accessor object.

Next, we build our base string and signature variables. Using those variables, we then generate the signature URI that will contain all of the necessary OAuth parameters to make a two-legged OAuth request. That final URI is returned from the function.

We can then use this function to make our request to YQL.

Making and parsing the request

We start out by storing the OAuth key and secret that we obtained when creating the OAuth application with the provider (in this case, Yahoo!). In addition, we store the URI to the firehose feed in YQL. This search query will look for any updates about hockey.

Once we have the variables in place, we generate the OAuth signed URI by making a request to our buildOAuthRequest(...) function that we covered earlier. With that in place, we can make our request and parse the returned data:

//OAuth keys and YQL query URI
var key = 'dj0yJmk9bTBDQzlLQUZ5NGpEVdHbzlNVEUyTmpRek5EazJNZy0tJnM9jZQ--';
var secret = 'c74a018f7db1d8de5ab2664ef5ab';
var url = 'http://query.yahooapis.com/v1/yql
           ?q=select%20*%20from%20social.updates.search%20
           where%20query%3D%22hockey%22&format=json';

//obtain 2-legged OAuth request URL using key, secret and YQL URL
var yqlURL = buildOAuthRequest(key, secret, url);

//make cross-domain AJAX request against OAuth signed URI
$.getJSON(yqlURL, function(data){
   response = '';

   //check if there are any results available
   if (data.query.count > 0){
      results = data.query.results.update;

      //loop through all results and display poster and title with links
      for (var i = 0; i < results.length; i++){
         response += '<p>From: <a href="'
                   + results[i].profile_profileUrl + '">'
                   + results[i].profile_nickname + '</a><br /><a href="'
                   + results[i].link + '">'
                   + results[i].loc_longForm + '</a></p>'
      }
   //if no response is present, display appropriate message
   } else {
      response = 'No results were found';
   }

   //print message to screen
   document.write(response);
});
</script>

</body>
</html>

We use the getJSON(...) JQuery method to make our cross-domain request to YQL. Once the request completes, we should get a response object containing the result set that we searched for.

If there are results available, we loop through all update elements and display who the update is from, linked to their profiles, followed by the title of the update, linked to the update source. If there are no results, we display an appropriate message.

Using this basic practice, we can generate two-legged OAuth requests to any provider or service.

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

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