This example demonstrates how to build a simple web JAX-RS application that can utilize JAX-RS client to query data from Google API using OAuth2 for authentication and authorization. This sample works only with browser as user interaction is needed to authorize the application for accessing user's open Google Tasks.

Contents

The mapping of the URI path space is presented in the following table:

URI path Resource class HTTP methods Description
/index.html GET contains for on which the user setups Client ID (application id).
/api/setup SetupResource GET Resource that initializes Client ID sent from form from index.html
/api/tasks TaskResource GET Resource with Google tasks
/api/oauth2/authorize AuthorizationResource GET Resource that will receive Authorization response from Google

How to setup the application

You need to have Google account and register into the Google API console https://code.google.com/apis/console. Register a new project.

Under 'Services' enable 'Tasks API'. Then go to the 'API Access' and create a new application. Choose Web Application as a type and define the redirect_uri. This you can define under 'Authorized Redirects URIs'. Put there the URI to your deployment. As you will probably run the app on the localhost, the URI may look for example like the following: "http://localhost:8080/oauth2-client-google-webapp/api/oauth2/authorize". The URI must point to the AuthorizationResource.authorize resource (so, it ends with /api/oauth2/authorize). If the URI is incorrectly entered into the API console, the authorization request will fail and the user will get an appropriate error message from Google (then go and fix the URI in the console).

Your new application will get and 'Client ID' and 'Client Secret'. Do not distribute these keys as they can be misused. You will need these keys to setup the application on index.html.

Running the Example

Run the example as follows:

mvn clean package jetty:run

This deploys current example using Jetty. Then go to http://localhost:8080/oauth2-client-google-webapp/ and enter Client ID and Client Secret of your application. Then continue to /api/tasks (following links), you will be redirected to the Google Authorization URI. Grant an access to your application. You will then be redirected back to "/api/oauth2/authorize" and authorization process will be finished. Immediately, you will be redirected back to the "/api/tasks". This time, the tasks will be get on the background from Google API and returned as HTML to your page.