First, you must download the required libraries:
Get your Google+ API Keys:
- Create a new Google Project
- Enable the API
- Under "Credentials" -> Create a new Client ID
- Now on the the Credentials screen, you should see Client ID, and Client Secret. We will need both of these for our application to work.
You can download an example Servlet Java file: GoogleAuthentication.java
If the user needs to be authenticated (doesn't already have a session), redirect the user like this to the authorization screen:
List<String> scopes = new ArrayList<String>();
scopes.add(Constants.OAUTH_SCOPES);
String authUrl = new AuthorizationCodeRequestUrl(
Constants.OAUTH_GOOGLE_AUTH_URL,
Constants.OAUTH_CLIENT_ID)
.setRedirectUri(Constants.OAUTH_REDIRECT_URL)
.setScopes(scopes)
.build();
response.sendRedirect(authUrl);
After Google authenticates them, they will redirect back to your site with a "code" in the query string:
http://localhost:8080/OAuth2/oauth2callback?code=4/nubUCslABZbPdh3SfBtZGjQkUhWqiZiCbSPEj3gf9Zk.In4jJp0AZW0WsjMf6whcw_6DoGmBlgI
Now, use that "code" to request additional information from Google about the user:
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
TokenResponse tokenResponse = new AuthorizationCodeTokenRequest(
httpTransport,
jsonFactory,
new GenericUrl(Constants.OAUTH_GOOGLE_TOKEN_URL), code)
.setRedirectUri(Constants.OAUTH_REDIRECT_URL)
.setClientAuthentication(new
ClientParametersAuthentication(
Constants.OAUTH_CLIENT_ID,
Constants.OAUTH_CLIENT_SECRET)).execute();
String accessToken = tokenResponse.getAccessToken();
Person person = new Plus.Builder(httpTransport, jsonFactory, null)
.setApplicationName("Example Application").build().people().get("me")
.setOauthToken(accessToken).execute();
session.setAttribute("email", person.getEmails().get(0).getValue());
session.setAttribute("name", person.getDisplayName());