Hide

Authenticate with a backend server

If you use Google Sign-In with an app or site that communicates with a backend server, you might need to identify the currently signed-in user on the server. To do so securely, after a user successfully signs in, send the user's ID token to your server using HTTPS. Then, on the server, verify the integrity of the ID token and retrieve the user's ID from the sub claim of the ID token. You can use user IDs transmitted in this way to safely identity the currently signed-in user on the backend.

Send the ID token to your server

After a user successfully signs in, get the user's ID token:

function onSignIn(googleUser) {
  var id_token = googleUser.getAuthResponse().id_token;
  ...
}

Then, send the ID token to your server with an HTTPS POST request:

var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://yourbackend.example.com/tokensignin');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
  console.log('Signed in as: ' + xhr.responseText);
};
xhr.send('idtoken=' + id_token);

Verify the integrity of the ID token

After you receive the ID token by HTTPS POST, you must verify the integrity of the token. To verify that the token is valid, ensure that the following criteria are satisfied:

  • The ID token is a JWT that is properly signed with an appropriate Google public key.
  • The value of aud in the ID token is equal to one of your app's client IDs. This check is necessary to prevent ID tokens issued to a malicious app being used to access data about the same user on your app's backend server.
  • The value of iss in the ID token is equal to accounts.google.com or https://accounts.google.com.
  • The expiry time (exp) of the ID token has not passed.
  • If your authentication request specified a hosted domain, the ID token has a hd claim that matches your Google Apps hosted domain.

Rather than writing your own code to perform these verification steps, we strongly recommend using a Google API client library for your platform, or calling our tokeninfo validation endpoint.

Calling the tokeninfo endpoint

The easiest way to validate an ID token is to use the tokeninfo endpoint. Calling this endpoint involves an additional network request that does most of the validation for you, but introduces some latency and the potential for network errors. For these reasons, it is suitable only for deployments with fewer than 100 monthly active users, as well as for debugging and informational purposes.

To validate an ID token using the tokeninfo endpoint, make an HTTPS POST or GET request to the endpoint, and pass your ID token in the id_token parameter. For example, to validate the token "XYZ123", make the following GET request:

https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123

If the token is properly signed and the iss and exp claims have the expected values, you will get a HTTP 200 response, where the body contains the JSON-formatted ID token claims. Here's an example response:

{
 "iss": "https://accounts.google.com",
 "sub": "110169484474386276334",
 "azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
 "email": "billd1600@gmail.com",
 "at_hash": "X_B3Z3Fi4udZ2mf75RWo3w",
 "email_verified": "true",
 "aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
 "iat": "1433978353",
 "exp": "1433981953"
}

Once you get these claims, you still need to check that the aud claim contains one of your app's client IDs. If it does, then the token is both valid and intended for your client, and you can safely retrieve and use the user's unique Google ID from the sub claim.

If you are a Google Apps for Work customer, you might also be interested in the hd claim, which indicates the hosted domain of the user. This can be used to restrict access to a resource to only members of certain domains. The absence of this claim indicates that the user does not belong to a Google Apps for Work hosted domain.

Using a Google API Client Library

Using one of the Google API Client Libraries is the recommended way to validate Google ID tokens in a production environment.

Java

To validate an ID token in Java, use the GoogleIdTokenVerifier object. For example:

import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;

...

GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
    .setAudience(Arrays.asList(CLIENT_ID))
    .build();

// (Receive idTokenString by HTTPS POST)

GoogleIdToken idToken = verifier.verify(idTokenString);
if (idToken != null) {
  Payload payload = idToken.getPayload();
  if (payload.getHostedDomain().equals(APPS_DOMAIN_NAME)
      // If multiple clients access the backend server:
      && Arrays.asList(ANDROID_CLIENT_ID, IOS_CLIENT_ID).contains(payload.getAuthorizedParty())) {
    System.out.println("User ID: " + payload.getSubject());
  } else {
    System.out.println("Invalid ID token.");
  }
} else {
  System.out.println("Invalid ID token.");
}

The GoogleIdTokenVerifier.verify() method verifies the JWT signature, the aud claim, the iss claim, and the exp claim. You must also verify the the hd claim (if applicable) with the Payload.getHostedDomain() method. If multiple clients access the backend server, manually verify the aud claim.

Python

To validate an ID token in Python, use the oauth2client.client.verify_id_token function. For example:

from oauth2client import client, crypt

# (Receive token by HTTPS POST)

try:
    idinfo = client.verify_id_token(token, CLIENT_ID)
    # If multiple clients access the backend server:
    if idinfo['aud'] not in [ANDROID_CLIENT_ID, IOS_CLIENT_ID, WEB_CLIENT_ID]:
        raise crypt.AppIdentityError("Unrecognized client.")
    if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
        raise crypt.AppIdentityError("Wrong issuer.")
    if idinfo['hd'] != APPS_DOMAIN_NAME:
        raise crypt.AppIdentityError("Wrong hosted domain.")
except crypt.AppIdentityError:
    # Invalid token
userid = idinfo['sub']

The oauth2client.client.verify_id_token function verifies the JWT signature, the aud claim, and the exp claim. You must also verify the iss claim and the hd claim (if applicable) by examining the object that verify_id_token returns. If multiple clients access the backend server, also manually verify the aud claim.

Google API Client Libraries are also available for .NET, PHP, Ruby, and other languages.