Thursday, January 24, 2013

Simple Google-OAuth2 from a Java client

OAuth is a powerful way to ensure that clients have access to appropriate resources, and the Google OAuth libs do a lot of the heavy lifting for you. But while the doco is pretty good I found it lacking when looking for the most appropriate way to authorize for a simple Java (non-web) application and that's probably to do with the rate at which this area is moving.

It turns out that there are excellent classes in the Google libraries to make OAuth absolutely trivial, in fact it's really only 3 lines:
  1. Construct your AuthorizationCodeFlow
  2. Construct your AuthorizationCodeInstalledApp
  3. Ask the InstalledApp to authorize the client
Here's the full code listing:


Now to make this happen you're going to need to include the relevant Google libs. You can find lots of good info about the libs here google-api-java-client, google-oauth-java-client and google-http-java-client.

The libs necessary for the above are: