Google Identity Toolkit

Google Identity Toolkit Integration Guide for Java Platform

Contents

  1. UI Changes
  2. Database schema change
  3. Integrating the GITkit Java client libaray

UI Changes

Use the Google Developers Console to generate your configuration code. For help with the Developers Console, consult our guide. The generated configuration code will look like the following sample but make sure to use the code generated for you by the console:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/googleapis/0.0.4/googleapis.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/jsapi"></script>
<script type="text/javascript">
   google.load("identitytoolkit", "1.0", {packages: ["ac"]});
</script>
<script type="text/javascript">
$(function(){
  window.google.identitytoolkit.setConfig({
    developerKey: "{your developer key}",
    companyName: "Your company",
    callbackUrl: "https://yoursite.com/callback", // must be a full URL
    userStatusUrl: "/userStatus", // these can just be partial paths
    loginUrl: "/login",
    signupUrl: "/signup",
    homeUrl: "/home",
    logoutUrl: "/logout",
    realm: "", // optional
    language: "en",
    idps: ["Gmail", "AOL", "Hotmail", "Yahoo"],
    tryFederatedFirst: true,
    useCachedUserStatus: false
  });
  $('#navbar').accountChooser();
});
</script>

Add this configuration code to the <head> of the pages on your site that need show the login widget. Optionally, add some CSS style for padding or right alignment. Please note that the callbackUrl needs to be the absolute path to your callback page, other Url parameters can use relative path.

Currently we support multiple languages for the widget UI. You can change the value of the parameter "language" in the javascript source code above, and the widget will be translated accordingly. The values of the parameter "language" are listed below:

Language Parameter value
Deutsch‬ de
English‬ en
English (UK)‬ en-GB
español‬ es
français‬ fr
italiano‬ it
日本語‬ ja
한국어‬ ko
简体中文‬ zh-CN
繁體中文 (台灣) zh-TW

Database schema change

Modify your Database schema, by adding a 'type' field to the User table to trace the type of a user. The "type" field indicates if an account is using federated login or the legacy username/password. Below is an example SQL command for MySql table 'user-account'.

 ALTER TABLE user-account ADD type VARCHAR(10);

Integrating the GITkit Java client libaray

  • Download client library

    For Web applications that uses Java, download the GITkit Java client library, and put it under the directory WEB-INF/lib of your web appliation..

  • Provide an implementation for AccountService interface

    You need to implement the com.google.apps.easyconnect.easyrp.client.basic.data.AccountService interface, through which the GITkit Java library access your user data.

    The AccountService interface has only 3 methods. For most web sites, you can simply use SQL-like DBL to query/change your Database directly.

    The Account class holds the information of an account in RP. Some common attribute names are predefined. An RP can set/get non-predefined attributes by {setAttribute}/{getAttribute} directly. It is included as part of the client library.

    AccountService.java
    
        /**
         * Returns the account info for an email, or null if not registered.
         * The email and accountType fields must be set in returned Account object.
         */
        Account getAccountByEmail(String email) {
          // To be implemented by RP.
        }
    
        /**
         * Returns whether the password is valid for the user.
         */
        boolean checkPassword(String email, String password) {
          // To be implemented by RP.
        }
    
        /**
         * Upgrade a legacy email account to federated login.
         * The response code may be OK, ACCOUNT_NOT_FOUND, ACTION_NOT_ALLOWED, UNKNOWN_ERROR.
         */
        ResponseCode toFederated(String email){
          // To be implemented by RP. Normally just update the user-account DB table.
        }
    
  • Config the SessionManager

    You also need to tell GITkit libary how to store and retrieve session state, which is managed either in server side or browser cookie. The Java client library predefined some implementation class, so you can just select and configure one of implementations below suitable to your site.

    • If your site uses server side session state, GITkit client library provides a SessionBasedSessionManager to use in this case. You only need to set the attribute name for session user (sessionUserKey) and IDP assertion (sessionIdpAssertionKey). See the below section for setting configuration parameters.
    • If your site uses cookies to store session state, GITkit client library provides a CookieBasedSessionManager to use in this case. To use CookieBasedSessionManager, you need to

      1. Set cookie-related configuration parameters: sessionCookieName, idpAssertionCookieName, maxAgeOfSession, maxAgeOfIdpAssertion, domain,path.

      2. Provide an implementation for TokenGenerator interface.

      This is because the cookie is saved on the client side, so there must be some way to check the value has not been changed by user. Normally your site should encrypt or sign the content in the cookie. In most case, your site should already has some way to do this, you only need to delegate the method in the interface to your existing functions.

      TokenGenerator.java
      
         /**
          * Creates the cookie value for a logged-in email
          */
           String generateSessionToken(String email) {
             // To be implemented by RP.
           }
      
          /**
          * Verifies the cookie value is valid. If valid, return the logged-in email address.
          */
          String verifySessionToken(String token) {
            // To be implemented by RP.
          }
      
          /**
          * Creates the cookie value to save the IDP assertion.
          */
          String generateIdpAssertionToken(JSONObject data) {
            // To be implemented by RP.
          }
      
          /**
          * Verifies the cookie value is valid. If valid, return the IDP assertion.
          */
          JSONObject verifyIdpAssertionToken(String token) {
            // To be implemented by RP.
          }
      

      Please note that the IDPAssertion JSONObject is the attributes sent by IDPs using the attribute exchange protocol, and the RP can save it in browser cookie for later retrieval. The key/value information of the IDPAssertion JSONObject can be found here (identitytoolkit.relyingparty.verifyAssertion).

    • If above two SessionManager do not meet your requirements, you can provide an implementation of SessionManager by yourself. See the Javadoc of SessionManager for more detail.

  • Set configuration parameters

    You can use the RpConfig.Builder class to build a RpConfig instance.
    See below table for the required parameters for different settings.

    Parameter Description Required for SessionBasedSessionManager Required for CookieBasedSessionManager
    sessionUserKey The attribute name used to save logged in account in the server side seesion object Yes No
    sessionIdpAssertionKey The attribute name used to save IDP assertion in the server side seesion object Yes No
    sessionCookieName The cookie name used to save logged in account in the cookie No Yes
    idpAssertionCookieName The cookie name used to save IDP assertion in the cookie No Yes
    maxAgeOfSession The cookie max age for seesion cookie No Yes
    maxAgeOfIdpAssertion The cookie max age for IDP assertion cookie No Yes
    domain The cookie domain No Yes
    path The cookie path No Yes
    homeUrl After user logged in, the URL to go Yes Yes
    signupUrl Redirect to this URL if a new account need to be created Yes Yes

    You should also remember to set your API key in the method invocation as the following code: Context.setApiClient(new ApiClient('your-API-key'));
    API key is the unique string to authenticate the API caller requests. It is assigned by Google Developers Console which is used to configure GITKit and do the dashboard statistics for your API key.

  • Register the above objects to Context

    For the config & implementation object be used by client library, you must register them to Context class when the web application start up. Normally you can do this in a ServletContextListener, which will be called when the web application start up. See the example code below to reigister and instantiate your implementation class.

    If your site supports server side session
    
          public class ContextLoader implements ServletContextListener {
            @Override
            public void contextDestroyed(ServletContextEvent evt) {
            }
    
            @Override
            public void contextInitialized(ServletContextEvent evt) {
              initEasyRpContext();
            }
    
            // Set config parameters.
            private void initEasyRpContext() {
              RpConfig config = new RpConfig.Builder()
                  .sessionUserKey("login_account")
                  .sessionIdpAssertionKey("idp_assertion")
                  .homeUrl("/home.jsp")
                  .signupUrl("/signup.jsp")
                  .build();
    
            //Suppose GaeAccountService is your own AccountService implementation.
    
            AccountService accountService = new GaeAccountService();
    
            // SessionBasedSessionManager fully supports server side session state.
            SessionManager sessionManager = new SessionBasedSessionManager(config);
    
            Context.setConfig(config);
            Context.setAccountService(accountService);
            Context.setSessionManager(sessionManager);
            Context.setApiClient(new
            ApiClient("your-API-key"));
            }
          }
    
    - or -
    If your site does not support server side session
    
     public class ContextLoader implements ServletContextListener {
            @Override
            public void contextDestroyed(ServletContextEvent evt) {
            }
    
            @Override
            public void contextInitialized(ServletContextEvent evt) {
              initEasyRpContext();
            }
    
            // Initialize the GITkit client library.
            private void initEasyRpContext() {
              RpConfig config = new RpConfig.Builder()
                  .sessionCookieName("EMAIL")
                  .idpAssertionCookieName("IDPASSERT")
                  .maxAgeOfSession(-1)
                  .maxAgeOfIdpAssertion(1800)
                  .domain("")
                  .path("/")
                  .homeUrl("/home.jsp")
                  .signupUrl("/signup.jsp")
                  .build();
    
              //Suppose GaeAccountService is your own AccountService implementation.
              AccountService accountService = new GaeAccountService();
    
              //Suppose YourTokenGenerator is your own TokenGenerator implementation.
              TokenGenerator generator = new YourTokenGenerator();
              SessionManager sessionManager = new CookieBasedSessionManager(config, accountService, generator);
    
              Context.setConfig(config);
              Context.setAccountService(accountService);
              Context.setSessionManager(sessionManager);
              Context.setApiClient(new
              ApiClient("your-API-key"));
    
            }
          }
    

  • Deploy LoginServlet, CallbackServlet, and your ServletContextListener

    The Java client library provides two servlets to support federated login: LoginServlet, CallbackServlet. You need to deploy them in your web.xml, together with your ServletContextListener. Below is a sample web descriptor.

    web.xml
    
    <servlet>
        <servlet-name>Login</servlet-name>
        <servlet-class>com.google.apps.easyconnect.easyrp.client.basic.servlet.LoginServlet</servlet-class>
      </servlet>
      <servlet>
        <servlet-name>Callback</servlet-name>
        <servlet-class>com.google.apps.easyconnect.easyrp.client.basic.servlet.CallbackServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>Login</servlet-name>
        <url-pattern>/login</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>Callback</servlet-name>
        <url-pattern>/callback</url-pattern>
      </servlet-mapping>
    
      <listener>
        <listener-class>
          com.google.apps.easyconnect.demos.easyrpbasic.servlet.ContextLoader
        </listener-class>
      </listener>
    

    Notes: the URL for these two servlets must be set correctly in the config of the JavaScript widget.


For optional tasks for RP to do to complete the GITkit integration, please refer to "Advanced Use".

Congratulations! Your site is now ready to support federated login.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.