I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 637 posts at DZone. You can read more from them at their website. View Full User Profile

OAuth in headless applications

10.13.2011
| 8287 views |
  • submit to reddit

OAuth is a wonderful standard: it allows users to give permissions to a third-party service to use theirs accounts on a website; but it works without forcing them to share their password like a phishing website would do.

The typical use of OAuth is for accessing the Facebook, Twitter or Google+ Api (social networks have lots of data to share). It works like a charm:

  1. An URL on socialnetwork.com is generated, that the user loads. A callback URL pointing to your application is attached as a GET param.
  2. Since the user is logged in (or he can log in with a simple form) on socialnetwork.com, a token is randomly generated and authorized. In case some permissions are required the user is prompted for approval.
  3. The user is redirected back to your application with the token, that now you can use to make requests. You never get to know the user's password.
A full explanation of OAuth is out of the scope of this post; what I want to tackle today is how to use OAuth inside an headless application such as Jenkins, PHPUnit or Ant.

Headless application?

An headless application does not have a real user interface, and which can run in background for days. Consider for example Jenkins performing builds for Continuous Integration; a Selenium server; or a crawler loading web pages all day on a server machine.

The point is in headless application you cannot send the user (who may be yourself) to a browser for approval at every reboot (for example because the process runs on a CI machine.) And usually, the social network can't redirect the user to the headless application with an HTTP Location header.

However, in the cases we are interested in a user is needed in order to make requests to the Api. Most social networks allows you to make many kinds of Api calls only after having logged in with an user.

Thus we have to split up our application in two parts: one (small) whose job is to obtain the authentication token, and one for using it as normal.

Obtaining the token

The assumption we make (see the relevant section at the end of the article) is that long-lived tokens are available for authorization. LinkedIn works like this, and I used my own user for authorizations to make Api calls for groups data.

I integrated an example of authorization from Scribe, the simplest Java library for OAuth. You load the URL provided by Scribe in a browser, follow the website-specific authorization procedure and then paste back the verifier parameter in Scribe.

However, I printed the token instead of using it immediately, and saved it in a .properties file which is ignored by Git via configuration, in order to avoid publishing it in a source code repository. Beware, a commit remains in the repository forever!

import java.io.IOException;
import java.util.Properties;
import java.util.Scanner;

import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.LinkedInApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

public class LinkedInConfigurator {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	    try {
		Properties properties = LinkedInDefault.getConfiguration();
		
		OAuthService service = new ServiceBuilder()
	        .provider(LinkedInApi.class)
	        .apiKey(properties.getProperty("apiKey"))
	        .apiSecret(properties.getProperty("apiSecret"))
	        .callback("http://localhost")
	        .build();
			
		Scanner in = new Scanner(System.in);
	
		System.out.println("Fetching the Request Token...");
		Token requestToken = service.getRequestToken();
		System.out.println("Got the Request Token!");
		System.out.println();
	
		System.out.println("Now go and authorize Scribe here:");
		System.out.println(service.getAuthorizationUrl(requestToken));
		System.out.println("And paste the verifier here");
		System.out.print(">>");
		Verifier verifier = new Verifier(in.nextLine());
		System.out.println();
		System.out.println("Trading the Request Token for an Access Token...");
		Token accessToken = service.getAccessToken(requestToken, verifier);
		System.out.println("The access token is [accessToken, accessSecret]: " + accessToken);
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}

}
The storing process is manual in my case, but you can easily save the token wherever you want.

Using the token

To use the access token, instantiate Scribe OAuthService again, along with the Token: you should pass to the constructor the two informations obtained from dumping it (token value and secret).

Now you can create requests and pass them to the service along with the token to be signed. The headless application acquire all the permissions that the user has in the Api.

import static org.junit.Assert.assertTrue;

import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;

public class ScribeLinkedInService implements LinkedInService {

	private OAuthService oauthService;
	private Token accessToken;

	public ScribeLinkedInService(OAuthService oauthService, Token accessToken) {
	    this.oauthService = oauthService;
	    this.accessToken = accessToken;
	}

	@Override
	public String getLastPostsResponse(int groupId, int numberOfPosts,
			long timestampToStartFrom) {
	    OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.linkedin.com/v1/groups/" + groupId + "/posts?count=" + numberOfPosts + "&modified-since=" + timestampToStartFrom);
	    oauthService.signRequest(accessToken, request);
	    Response response = request.send();
	    return response.getBody();
	}

}

Terms Of Service and expiration

Before jumping to implementation, verify that your social network of choice gives you tokens that you can legally store and do not expire in half an hour.

LinkedIn is where I tested this approach and it explicitly said that if the user specifies so, token are durable and do not expire until explicitly revoked. In fact I'm still using one obtained last week for running my integration tests.

Facebook by default gives you a parameter (in the redirect URL) along with the token that tells you how many seconds the token will last. However, if you ask the user for the offline_access permission in the scope parameter of the OAuth dialog, the token will have an infinite expiry time.

It's not really secure for a user to relinquish the access to his account to the application forever, but I presume you're using your own user (or a dummy one) like I am with LinkedIn. Then, you're already saving your password in the browser, aren't you?

Twitter does not currently expire access tokens, unless your application is suspended or the user rejects it from their settings page. Moreover, it offers a wide public portion of its Api where you do not need an authenticated user to perform requests; these tricks may not be neeeded.

FourSquare does not expire tokens, but may do so in the future.

Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Nicolas Frankel replied on Thu, 2011/10/13 - 5:46am

Interesting, I didn't know about Scribe. Thanks!

Mozart Brocchini replied on Thu, 2011/10/13 - 7:41pm

Great post !

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.