Close

Servlet - Login with Google OAuth API

[Last Updated: Mar 9, 2017]

OAuth is an open standard for authorization. It is a way to log users in to our application by delegating authenticate process to the third party trustworthy services. In this tutorial we are going to quickly walk through how to use google API to have our users login with their google/gmail accounts.

Create your project with Google developer console

Follow the steps here

The most important thing in the developer project is your 'Client ID' and your url. I used http://localhost:9998/ for this example.



Create web page.

Our index.jsp page. Notice google 'platform.js' the the meta header which are google sign-in api specific.

In this example the user will go to index.jsp page first. After successful authentication with gmail account, the user will be redirected to login servlet and then after authentication verification and extracting user info, it will be redirected to welcome-page.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://apis.google.com/js/platform.js" async defer></script>

<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id"
     content="----- your google client id here -----------">

<title>Servlet OAuth example</title>
</head>
<body>
	<h2>Servlet OAuth example</h2>
	<br>
	<div class="g-signin2" data-onsuccess="onSignIn"></div>

  <script>
      //google callback. This function will redirect to our login servlet
      function onSignIn(googleUser) {
         var profile = googleUser.getBasicProfile();
         console.log('ID: ' + profile.getId());
         console.log('Name: ' + profile.getName());
         console.log('Image URL: ' + profile.getImageUrl());
         console.log('Email: ' + profile.getEmail());
         console.log('id_token: ' + googleUser.getAuthResponse().id_token);

         //do not post all above info to the server because that is not secure.
         //just send the id_token

         var redirectUrl = 'login';

         //using jquery to post data dynamically
         var form = $('<form action="' + redirectUrl + '" method="post">' +
                          '<input type="text" name="id_token" value="' +
                           googleUser.getAuthResponse().id_token + '" />' +
                                                                '</form>');
         $('body').append(form);
         form.submit();
      }

   </script>
</body>
</html>

In above code, don't forget to replace you google client id in meta 'google-signin-client_id'.



Create login servlet

We added google api dependencies in pom.xml (included in the example project at the bottom.)

Here's how we going to extract all information from 'id_token' by using google api.

package com.logicbig.example;
    .......
@WebServlet(urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost (HttpServletRequest req,
                        HttpServletResponse resp)
                        throws ServletException, IOException {

        resp.setContentType("text/html");

        try {
            String idToken = req.getParameter("id_token");
            GoogleIdToken.Payload payLoad = IdTokenVerifierAndParser.getPayload(idToken);
            String name = (String) payLoad.get("name");
            String email = payLoad.getEmail();
            System.out.println("User name: " + name);
            System.out.println("User email: " + email);

            HttpSession session = req.getSession(true);
            session.setAttribute("userName", name);
            req.getServletContext()
               .getRequestDispatcher("/welcome-page.jsp").forward(req, resp);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

package com.logicbig.example;

import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;

public class IdTokenVerifierAndParser {
    private static final String GOOGLE_CLIENT_ID = " --- use your google client id here --";

    public static GoogleIdToken.Payload getPayload (String tokenString) throws Exception {

        JacksonFactory jacksonFactory = new JacksonFactory();
        GoogleIdTokenVerifier googleIdTokenVerifier =
                            new GoogleIdTokenVerifier(new NetHttpTransport(), jacksonFactory);

        GoogleIdToken token = GoogleIdToken.parse(jacksonFactory, tokenString);

        if (googleIdTokenVerifier.verify(token)) {
            GoogleIdToken.Payload payload = token.getPayload();
            if (!GOOGLE_CLIENT_ID.equals(payload.getAudience())) {
                throw new IllegalArgumentException("Audience mismatch");
            } else if (!GOOGLE_CLIENT_ID.equals(payload.getAuthorizedParty())) {
                throw new IllegalArgumentException("Client ID mismatch");
            }
            return payload;
        } else {
            throw new IllegalArgumentException("id token cannot be verified");
        }
    }
}

Don't forget to replace your google client id for constant GOOGLE_CLIENT_ID in above class.




Example Project

Run war using embedded tomcat server from project root:

    mvn clean install tomcat7:run-war

Access app at

 http://localhost:9998/google-oauth-example/

On signing in, the page will be redirected to welcome-page.jsp


Dependencies and Technologies Used:

  • Java Servlet API 3.0.1
  • Google APIs Client Library for Java 1.22.0
  • Google HTTP Client Library for Java 1.22.0: Google HTTP Client Library for Java. Functionality that works on all supported Java platforms, including Java 5 (or higher) desktop (SE) and web (EE), Android, and Google App Engine.
  • Gson 2.7
  • Jackson extensions to the Google HTTP Client Library for Java. 1.22.0
  • Google OAuth2 API v2-rev120-1.22.0 v2-rev120-1.22.0
  • Google APIs Client Library for Java 1.22.0
  • Google+ API v1-rev453-1.22.0 v1-rev453-1.22.0
  • JDK 1.8
  • Maven 3.0.4

Google Oauth Servlet Example Select All Download
  • google-oauth-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • LoginServlet.java
          • webapp

    See Also