The newest version of Google Identity Toolkit has been released as Firebase Authentication. It includes upgraded client SDKs, open source UI libraries, session management and integrated email sending service for forgotten password flows.

New projects should use Firebase Authentication. To migrate an existing project from Identity Toolkit to Firebase Authentication, see the migration guide.

Implement required endpoints

Overview

Identity Toolkit aims to require as little server-side logic as possible from your server, but there are a few steps you need to take to display the pages with the widgets and tie in to your user database.

Rendering the page with the sign in widget

This page should be simple. The url you chose earlier for "Widget URL" needs to respond with the template you built in the last step (Set up UI widgets):

  • Includes the JavaScript code to configure the behavior of the sign in page (you did this in the previous section titled Set up UI widgets).
  • Contains an HTML <div> where the sign in widget will be shown

Sign-in Success URL

Generally, websites perform session management (considering a user signed in) based on the use of browser cookies. Usually, your Web framework takes care of this, and abstracts away the cookies behind some flavor of session variable.

When a website finishes the sign in flow for a user, its central sign in system creates a session, which usually involves issuing a session cookie, a digitally signed (and sometimes encrypted) blob with information about the account of the signed in user. If the site has pages that require a user to be signed in, then the server-side logic for those URLs usually includes the code needed to confirm there is a valid login cookie, and extract the account information.

Your session management needs to be tweaked to work with Identity Toolkit. We’ll talk in terms of creating sessions, setting values in them, and retrieving values from them, with the understanding that this is cookie-based.

You can see a full example of how to integrate Identity Toolkit login with your web platform's session management in our Go quickstart.

Understanding the Identity Toolkit cookie/token

You can think about the cookie as your user’s credential. It’s secure, and is the same format no matter how a user signs in to your site

When a user signs in successfully on a Identity Toolkit-enabled site, Identity Toolkit’s widgets set a cookie named “gtoken”. It is a JSON Web Token (JWT), a cryptographically-signed JSON object encoded in base 64. The Identity Toolkit JWT is very similar to an OpenID Connect ID token and we will refer to this as the Identity Toolkit ID Token. It does not conform to the OpenID Connect specification in one important way. The user_id field in an OIDC ID token is the identifier of the user at the IDP. The user_id field in the Identity Toolkit ID Token is a global identifier, unique across all IDPs, for this user, in the context of your site or app. It is not shared with other sites or apps which use Identity Toolkit. In other words, Identity Toolkit does not provide a global identifier across different developers (relying parties).

It is critical that you validate the Identity Toolkit ID Token before you use it. Most programming languages have JWT libraries to simplify this task, and each of the quick-start apps include a library to help with this.

After the token has passed the cryptographic test, be sure to check that:

  1. The token is not expired. The current clock time in seconds must be less than exp value in the token. The Identity Toolkit token has an expiration of two weeks.

  2. The token is indeed issued to your site. The aud field in the token must match your client ID that you registered for Identity Toolkit at the Developer Console.

Most JWT libraries combine the validation with the work of decoding the base64 and parsing the JSON, so this is apt to be convenient and straightforward.

Handling a sign-in event

When you get a request to your Sign In Success URL, you should check for the Identity Toolkit cookie and verify it. If either of these fails, you should treat the user as unauthenticated. If success, then you should see if you have seen the user before.

An Identity Toolkit ID

Because there is no explicit notification from Identity Toolkit to your app when a new account is created, it is normal that the user_id in the Identity Toolkit cookie may not appear in your own per-app user database.

  • If you have never seen that user before (the user_id is not in your database), you should get the user’s information and create a new user in your database based on that user_id. Remember that, although the Identity Toolkit ID Token includes an email address, the value of the user_id field is always a better choice for persisting and retrieving per-user information. Most obviously, it can survive email-address changes.

    Complete the user’s profile information by Getting information for users (see below). Do keep in mind though that your site may also need additional information than what is provided by Identity Toolkit APIs. Identity Toolkit doesn’t remove the need for you to interact with a new user to acquire special information relative to your app, for example shoe size or favorite color.

  • If you have seen that user (the user_id is in your database), you should still get the user’s information to see if it has been updated since you originally stored it in your user database. One of the advantages of using identity providers is that the user may be more likely to keep their account with the IDP updated than with your app. Users will generally regard your app more highly if you keep it up to date with their most relevant data.

Getting information for users

While the Identity Toolkit ID Token’s payload includes a certain amount of useful user information (email, name, photo URL) you can also retrieve per-user info stored in the Identity Toolkit user database by accessing the getAccountInfo API. Typically, this API requires you have a Identity Toolkit ID Token to use as a bearer access token access the info. Your server can access this information without having the user present by setting up a Service Account as described earlier under Configure service.

Keeping track of whether a user is signed in

Normally, in the past, you would begin each request by checking whether you had a valid session active and, if not, dispatching to your sign-in module. A Identity Toolkit-enabled app should do the same, except the redirect should be to your widget url with the url parameter mode=select. For example if the user has no active session on your site you may redirect to https://yoursite.com/signin?mode=select

As an optimization, if you find no active session, depending on your risk management needs, you could check to see whether there is a Identity Toolkit cookie and if so, validate it and extract the user’s identity. The stated expiration time is two weeks after the issue time, but you can choose whether to verify against that time or use another length of time from the issue time depending on your risk needs.

Alternate methods for managing a local session state

In addition to the method of minting your own cookies to manage session state, you could alternately use one of these other techniques to create and validate session cookies:

  • Hybrid Cookie: You can take a hybrid approach and 1) rely on the existing Identity Toolkit token without any extra confirmation or signing bits and 2) make a copy of the Identity Toolkit cookie and sign it with the your encryption key as a way to confirm it has been validated. The latter cookie can be set as an HTTP-only too, but the regular Identity Toolkit cookie will not be an HTTP only cookie. If you only want to use HTTP only cookies, then you must either mint your own or make a copy.

  • Identity Toolkit cookie only: If the website is very simple, then it can just rely on the existing basic Identity Toolkit cookie. Doing this will mean that your site will not have any control over the session dynamics and the user’s session will last for the two week duration of the Identity Toolkit cookie.

    You will still need to validate the signature on the Identity Toolkit ID token and extract the basic account information.

Sign-out URL

If you’re using the user information box, when the user signs-out, Identity Toolkit will delete the Identity Toolkit cookie and redirect the user to the Signout URL. You should implement logic on this endpoint that ends your own session.

If you're not using the user information box, feel free to delete the Identity Toolkit cookie and end your own session whenever you wish.

Send Email URL

To complete the closed loop system that allows users to authenticate to your site via IDP or password, you also need to support to send them emails in the case of password resets and email verification. The UI flow is largely managed by Identity Toolkit but you will have to implement the email sending functionality so that you can add your own messaging and branding. Because many of the largest email providers use SPF and DKIM to authenticate that messages really come from your domain, this will also reduce the chance that these are marked as spam.

The flow proceeds as follows:

  1. The user clicks a forgot password or change email link.

  2. The Identity Toolkit javascript will send an HTTP POST request to your Send Email/Forgot Password URL with relevant information.

  3. Forward this information to Google Identity Toolkit. If you are not using a web client library (e.g. Java, PHP), please refer to the Handling Email Changes and Handling Forgotten Passwords sections. Otherwise,

    • Forward the HTTP request to the GetOobResult method in your client library. In Java, for example, you would call GitkitClient.getOobResponse(HttpServletRequest req).
    • Extract the action link from the OOB response and send it in an email to your user.
    • Copy the OOB response to the HTTP response to fill in the UI.

  4. If successful, return {"success": true} in the response body. Otherwise, return {"success": false}.

For example of implementing the Send Email URL, check out the Go quickstart.

Adding Identity Providers

Once you have Sign in with Google and password accounts working, you will likely want to offer other sign in options for your users.

Facebook

  1. Create a Facebook application at developers.facebook.com.
  2. In the settings page for your Application, click the "Add Platform" button. Select Web, then add your website URL.
  3. Copy your Facebook App ID into the Client ID field and the Facebook App Secret into the Secrety Key field in the Identity Toolkit configuration page. Be sure to click "save" when you are done.
  4. Add "facebook" to the idps field in the config variable for your javascript widget.

Twitter

  1. Go to the Twitter Application Management page and create a new app.
  2. Under "Callback URL" you will have to write the URL to where you will be hosting Identity Toolkit.
  3. Once the app is created, from your app dashboard go to "Keys and Access Tokens" and copy the Consumer key and Consumer secret. Then go to the Identity Toolkit configuration page, enable Twitter as a provider and paste in your Consumer Key and Secret.
  4. Add "twitter" to the idps field in the config variable for your javascript widget.

Yahoo

To enable Yahoo login, note that you need to have the Google Identity Toolkit javascript widget running at your identitytoolkit.server_widget_url.

  1. Follow these instructions to enable your Yahoo app. You should register as a website using your widget_url.
  2. Once you have registered you app, copy the Consumer Key and Consumer Secret to the Identity Toolkit configuration page.
  3. Add "yahoo" to the idps field in the config variable for your javascript widget.
  4. Set the roll-out percentage in the settings console as appropriate. Be sure to click "save" when you are done.

Microsoft

To enable Microsoft login, note that you need to have the Google Identity Toolkit javascript widget running at your identitytoolkit.server_widget_url.

  1. Follow these instructions to enable your Microsoft app. You should register as a website using your widget_url.
  2. Once you have registered you app, copy the Client ID and Secret Key to the Identity Toolkit configuration page.
  3. Add "microsoft" to the idps field in the config variable for your javascript widget.
  4. Set the roll-out percentage in the settings console as appropriate. Be sure to click "save" when you are done.

AOL

To enable AOL login, note that you need to have the Google Identity Toolkit javascript widget running at your identitytoolkit.server_widget_url.

  1. Add "aol" to the idps field in the config variable for your javascript widget. Be sure to click "save" when you are done.
  2. Set the roll-out percentage in the settings console as appropriate. Be sure to click "save" when you are done.

Paypal

To enable Paypal login, note that you need to have the Google Identity Toolkit javascript widget running at your identitytoolkit.server_widget_url.

  1. Follow these instructions to enable your Paypal app. You should register as a website using your widget_url.
  2. Once you have registered you app, copy the Client ID and Secret Key to the Identity Toolkit configuration page. Be sure to click "save" when you are done.
  3. Add "paypal" to the idps field in the config variable for your javascript widget.
  4. Set the roll-out percentage in the settings console as appropriate. Be sure to click "save" when you are done.

Advanced Topics

Decoding the Identity Toolkit ID Token

An ID Token is a JWT containing a set of name/value pairs. Here’s an example:

{"iss" : "https://identitytoolkit.google.com/",
"user_id" : 829A8CD24E,
"aud" : "622215261071.apps.googleusercontent.com",
"provider_id" : "google.com",
"iat" : 1408553860,
"exp" : 1409763460,
"email" : "jsmith@example.com",
"verified": "true" }

The fields used by Identity Toolkit are:

Parameter Present? Description
iss always The Issuer Identifier for the Issuer of the response. This will always be "https://identitytoolkit.google.com/".
user_id always The user’s local ID on your site. Identity Toolkit will generate new user_id numbers once you begin to use it for new user sign-ups.
aud always Identifies the audience that this ID Token is intended for. It must be one of the OAuth 2.0 Client IDs of your application.
provider_id sometimes The base URL of the identity provider.
iat always An integer giving the time the ID token was issued, in seconds since the beginning of 1970, UTC.
exp always An integer giving the time the ID Token expires, in seconds since the beginning of 1970, UTC.
email sometimes The user’s email address. This may not be unique and is not suitable for use as a primary key.
verified sometimes True if the user's e-mail address has been verified; otherwise false. If the user goes through the Identity Toolkit email recovery flow and activates the URL, Identity Toolkit will mark this as verified.

Handling Email Changes

You should not need to follow these steps if using a language-specific library provided with the web quick start apps (not Android and iOS). These libraries include a method that will handle the OOB request.

In this case the user is already signed in, but we need to verify that they own the new email address. Identity Toolkit javascript will send an HTTP POST to your Send Email URL with a post body with action=changeEmail&email=...&newEmail=... You then need to make a request to Google Identity Toolkit’s out-of-band confirmation-code endpoint, though since this requires the use of a Service Account, it is a multi-step process as follows:

  1. Using the developer console, register a service account in the same project as your Identity Toolkit client and download the private key that it generates. You did this in the Configure service step.

  2. Construct a JWT signed with the RS256 algorithm using the service-account private key. The details of this are language-specific, but most languages have libraries that make it reasonably straightforward. Note that the the Developer Console provides the private key in .p12 file format, but some libraries require the use of .pem. Conversion between the two formats may be accomplished using the openssl command-line utility. The claims in the JWT, i.e. the JSON key-value pairs used to construct it, are:

    {
     "iss" : "<service-account email from developer console>",
     "scope": "https://www.googleapis.com/auth/identitytoolkit",
     "aud": "https://accounts.google.com/o/oauth2/token",
     "iat": <current time as integer seconds since beginning of 1970>,
     "exp": <expiry time, typically current time + 3600>
    }
    
  3. Send an HTTP POST to the token endpoint (https://accounts.google.com/o/oauth2/token) whose body is URL-form-encoded data containing two key-value pairs:

    grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer
    
    assertion=<the JWT constructed in step 2>
    
  4. The HTTP POST, if it succeeds, will return a JSON body, all of whose fields can be ignored except that named access_token. Extract that value. Send an HTTP POST to the out-of-band code endpoint getOobConfirmationCode containing the details about the CAPTCHA challenge and response, encoded in a JSON message as follows:

    {
     "kind": "identitytoolkit#relyingparty",
     "requestType": "NEW_EMAIL_ACCEPT",
     "email": "<from the Identity Toolkit POST to your Change email endpoint>",
     "newEmail": "<from the Identity Toolkit POST to your Change email endpoint>",
     "idToken": "<string value of the Identity Toolkit cookie, called gtoken by default>"
     "userIp": "<IP address the Identity Toolkit POST came from>"
    }
    

The POST will need to be accompanied by an HTTP header as follows:

Authorization: Bearer <access_token value from step 4>
  1. The out-of-band code endpoint will return a JSON body; if there is an error it will contain a top-level member whose name is error. If it succeeds, it will contain a top-level member named oobCode.

  2. Extract the oobCode value and use it to construct a URL as follows:

    <Your Identity Toolkit Widget URL>?mode=changeEmail&oobCode=<oobCode value>
    
  3. Construct an email (to the address provided in the Identity Toolkit POST to your Send Email endpoint), including a link to the URL constructed in step 7, asking that the user follow this link in order to verify their email. When you compose the email, you should also look up their language preference so that you can send a message localized to their language.

The user will have one hour to click on the recovery link in the email. When they do, they will be taken back to a Identity Toolkit widget and the email on file will be changed.

Handling Forgotten Passwords

You should not need to follow these steps if using a language-specific library provided with the web quick start apps (not Android and iOS). These libraries include a method that will handle the OOB request.

Here, the user is currently un-authenticated and may be trying to brute force attack your account system. To defend against this, a CAPTCHA is required. When the user enters their CAPTCHA response, Identity Toolkit javascript sends an HTTP POST describing the interaction to your Send Email URL with a post body like action=resetPassword&email=...&challenge=...&response=...

You then need to make a request to Google Identity Toolkit’s out-of-band confirmation-code endpoint, though since this requires the use of a Service Account, it is a multi-step process as follows:

  1. Using the developer console, register a service account in the same project as your Identity Toolkit client and download the private key that it generates.

  2. Construct a JWT signed with the RS256 algorithm using the service-account private key. The details of this are language-specific, but most languages have libraries that make it reasonably straightforward. Note that the the Developer Console provides the private key in .p12 file format, but some libraries require the use of .pem. Conversion between the two formats may be accomplished using the openssl command-line utility. The claims in the JWT, i.e. the JSON key-value pairs used to construct it, are:

    {
     "iss" : "<service-account email from developer console>",
     "scope": "https://www.googleapis.com/auth/identitytoolkit",
     "aud": "https://accounts.google.com/o/oauth2/token",
     "iat": <current time as integer seconds since beginning of 1970>,
     "exp": <expiry time, typically current time + 3600>
    }
    
  3. Send an HTTP POST to the token endpoint (https://accounts.google.com/o/oauth2/token) whose body is URL-form-encoded data containing two key-value pairs:

    grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer`
    
    assertion=<the JWT constructed in step 2>`
    
  4. The HTTP POST, if it succeeds, will return a JSON body, all of whose fields can be ignored except that named access_token. Extract that value.

  5. Send an HTTP POST to the out-of-band code endpoint getOobConfirmationCode containing the details about the CAPTCHA challenge and response, encoded in a JSON message as follows:

    {
     "kind": "identitytoolkit#relyingparty",
     "requestType": "PASSWORD_RESET",
     "email": "<from the Identity Toolkit POST to your Send Email endpoint>",
     "challenge": "<from the Identity Toolkit POST to your Send Email endpoint>",
     "captchaResp": "<from the Identity Toolkit POST to your Send Email endpoint>",
     "userIp": "<IP address the Identity Toolkit POST came from>"
    }
    

The POST will need to be accompanied by an HTTP header as follows:

Authorization: Bearer <access_token value from step 4>
  1. The out-of-band code endpoint will return a JSON body; if there is an error it will contain a top-level member whose name is error. If it succeeds, it will contain a top-level member named oobCode.

  2. Extract the oobCode value and use it to construct a URL as follows:

    <Your Identity Toolkit Widget URL>?mode=resetPassword&oobCode=<oobCode value>
    
  3. Construct an email (to the address provided in the Identity Toolkit POST to your Send Email endpoint), including a link to the URL constructed in step 7, asking that the user follow this link in order to launch the password-recovery process. When you compose the recovery email, you should also look up their language preference so that you can send a recovery email localized to their language.

The user will have one hour to click on the recovery link in the email. When they do, they will be taken back to a Identity Toolkit widget which leads them through the creation of a new local password for your site.