Home > OAuth Signpost > OAuth in java – the Signpost library

OAuth in java – the Signpost library

For a quick command line java example, we’ll be using the oauth-signpost library, a java library with OAuth support that can also be used in Android projects (see Implementing the OAuth flow in Android) . The sample code below illustrates how easy it is to orchestrate the OAuth workflow from a java runtime. The sample program will use a command-line approach guiding you to the oauth flow. It will basically do the following steps :

  • get a request token
  • ask you to authorize access
  • exchange the authorized token for an access token
  • retrieve your contacts
oauth-commandline-logo


Everything is implemented in a single class for simplicity. In order to run the program, you’ll need to include the following dependencies

  • signpost-core-1.2.1.1.jar
  • signpost-commonshttp4-1.2.1.1.jar
  • commons-codec-1.4.jar
  • commons-logging-1.1.1.jar
  • httpclient-4.0.1.jar
  • httpcore-4.0.1.jar

Signpost has a default implementation using the java.net.HttpURLConnection class (included in the signpost-core library). However, due to an Android bug developers should use the apache commons implementation (the CommonsHttpOAuth* classes in the signpost-commonshttp jar).

On the right, you can see an Eclipse project view of the project, containing the single class we’ll be discussing here. oauth signpost commandline eclipse project

The first thing we need to do is setup some OAuth specific parameters such as

  • the consumer key and consumer secret (needed to identify the app that requires access)
  • the request , authorize and access endpoints from Google
  • the scope of our request
  • the actual request we can to perform after having received an access token
	private static final String CONSUMER_KEY = "anonymous";
	private static final String CONSUMER_SECRET = "anonymous";

	private static final String REQUEST_URL = "https://www.google.com/accounts/OAuthGetRequestToken";
	private static final String AUTHORIZE_URL = "https://www.google.com/accounts/OAuthAuthorizeToken";
	private static final String ACCESS_URL = "https://www.google.com/accounts/OAuthGetAccessToken";
	private static final String CALLBACK_URL = "";

	private static final String SCOPE = "https://www.google.com/m8/feeds/";
	private static final String ALL_CONTACTS_REQUEST = "https://www.google.com/m8/feeds/contacts/default/full";

Signpost has object representations of the consumer and provider.

The consumer is initialized with his consumer key and consumer secret
The provider is initialized with the OAuth endpoints (request , authorize and access)

		this.consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,
				CONSUMER_SECRET);
		this.provider = new CustomOAuthProvider(REQUEST_URL
				+ "?scope=" + URLEncoder.encode(SCOPE, "utf-8"),
				ACCESS_URL, AUTHORIZE_URL);

Now that we have the consumer and provider setup, we’ll retrieve the URL that we need to a request token from the provider using the following code

String url = provider.retrieveRequestToken(consumer,CALLBACK_URL)

The retrieveRequestToken will actually do 2 things. It will connect to google asking for a request token. When it receives a request token (and token secret), it will then generate the URL required for authorizing access. When this url is entered in the browser, Google will present a page where you can grant access to your contacts. Once you’ve granted access, an oauth_verifier will be sent back as a request param.

The oauth_verifier is needed to upgrade the authorized token to an access token. Upgrading the authorized token to an access token is done using the following code (not that you need to copy-paste the oauth_verifier string from the previous request before continuing.

		String oauth_verifier = scanner.nextLine();
		provider.retrieveAccessToken(consumer, URLDecoder.decode(oauth_verifier,"UTF-8"));

Now that we have our access token, we can interact with Google to retrieve the contacts. This is done using a simple GET request.

		token = consumer.getToken();
		secret = consumer.getTokenSecret();

		consumer.setTokenWithSecret(token, secret);

		System.out.println(doGet(ALL_CONTACTS_REQUEST, consumer));

The full sourcecode can be found here :

package com.ecs.google.oauth;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Scanner;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;

public class BootstrapOAuth {

	private static final String ALL_CONTACTS = "https://www.google.com/m8/feeds/contacts/default/full";

	private static final String CONSUMER_KEY = "anonymous";
	private static final String CONSUMER_SECRET = "anonymous";

	private static final String SCOPE = "https://www.google.com/m8/feeds/";
	private static final String REQUEST_URL = "https://www.google.com/accounts/OAuthGetRequestToken";
	private static final String AUTHORIZE_URL = "https://www.google.com/accounts/OAuthAuthorizeToken";
	private static final String ACCESS_URL = "https://www.google.com/accounts/OAuthGetAccessToken";

	private static final String CALLBACK_URL = "test";

	private OAuthProvider provider;
	private OAuthConsumer consumer;

	public static void main(String[] args) throws Exception {
		new BootstrapOAuth().initialize();
	}

	public void initialize() throws Exception {
		Scanner scanner = new Scanner(System.in);

		String secret = null;
		String token = null;

		this.consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,
				CONSUMER_SECRET);
		this.provider = new CommonsHttpOAuthProvider(REQUEST_URL
				+ "?scope=" + URLEncoder.encode(SCOPE, "utf-8"),
				ACCESS_URL, AUTHORIZE_URL);

		String url = provider.retrieveRequestToken(consumer,CALLBACK_URL);
		System.out.println("1. Copy paste the following url in your browser : ");
		System.out.println(url);
		System.out.println("2. Grant access ");
		System.out.println("3. Copy paste the  " + OAuth.OAUTH_VERIFIER + "parameter here :");
		String oauth_verifier = scanner.nextLine();

		provider.retrieveAccessToken(consumer, URLDecoder.decode(oauth_verifier,"UTF-8"));

		token = consumer.getToken();
		secret = consumer.getTokenSecret();

		consumer.setTokenWithSecret(token, secret);

		System.out.println(doGet(ALL_CONTACTS, consumer));

	}

	private String doGet(String url,OAuthConsumer consumer) throws Exception {
		DefaultHttpClient httpclient = new DefaultHttpClient();
    	HttpGet request = new HttpGet(url);
    	System.out.println("Using URL : " + url );
    	consumer.sign(request);
    	HttpResponse response = httpclient.execute(request);
    	System.out.println("Statusline : " + response.getStatusLine());
    	InputStream data = response.getEntity().getContent();
    	BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(data));
        String responeLine;
        StringBuilder responseBuilder = new StringBuilder();
        while ((responeLine = bufferedReader.readLine()) != null) {
        	responseBuilder.append(responeLine);
        }
        return responseBuilder.toString();
	}
}

References :