Verify the Google ID token on your server sideStay organized with collectionsSave and categorize content based on your preferences.
Page Summary
Google ID tokens are submitted to your login endpoint via an HTTPPOSTrequest with the parameter namecredential.
To validate and consume the ID token, you should first verify the Cross-Site Request Forgery (CSRF) token using the double-submit-cookie pattern.
The ID token is returned in thecredentialfield, not theg_csrf_tokenfield.
After confirming the token's validity, you can use the Google ID token information to determine the account status of the user on your site (unregistered, existing, or returning federated user).
Only use the Google ID token'ssubfield as the unique identifier for the user and associate it with the user in your account management system.
When using Google Identity Services or OAuth 2.0 authorization code flow, Google
returns the ID token using POST method to the redirect endpoint. Alternatively,
the OIDC implicit flow uses a GET request. Consequently, your application is
responsible to securely transmit these received credentials to your server.
GET
This is the implicit flow, the ID token is returned within the URL
fragment, which the client-side JavaScript must parse. Your application
is responsible for implementing its own validation mechanisms to ensure
the request's authenticity and prevent attacks like CSRF.
The ID token is sent back as thecredentialfield. When
preparing to send the ID Token to the server the GIS library automatically
adds theg_csrf_tokento the header cookie and the request
body. This is an example POST request:
Extract the CSRF token value from theg_csrf_tokencookie.
Extract the CSRF token value from the request body. The GIS library
includes this token in the POST request body as a parameter, also namedg_csrf_token.
Compare the two token values
If both the values are present and match completely, the request
is considered legitimate and originated from your domain.
If the values are not present or does not match, the request has to
be rejected by the server.
This check ensures that the request was initiated from JavaScript running on
your own domain, as only your domain can access theg_csrf_tokencookie.
Verify the ID token.
To verify that the token is valid, ensure that the following
criteria are satisfied:
The ID token is properly signed by Google. Use Google's public keys
(available inJWKorPEMformat)
to verify the token's signature. These keys are regularly rotated; examine
theCache-Controlheader in the response to determine when
you should retrieve them again.
The value ofaudin 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 ofissin the ID token is equal toaccounts.google.comorhttps://accounts.google.com.
The expiry time (exp) of the ID token has not passed.
If you need to validate that the ID token represents a Google Workspace or Cloud
organization account, you can check thehdclaim, which indicates the hosted
domain of the user. This must be used when restricting access to a resource to only members of
certain domains. The absence of this claim indicates that the account does not belong to a
Google hosted domain.
Using theemail,email_verifiedandhdfields, you can determine if
Google hosts and is authoritative for an email address. In the cases where Google is authoritative,
the user is known to be the legitimate account owner, and you may skip password or other
challenge methods.
Cases where Google is authoritative:
emailhas a@gmail.comsuffix, this is a Gmail account.
email_verifiedis true andhdis set, this is a Google Workspace account.
Users may register for Google Accounts without using Gmail or Google Workspace. Whenemaildoes not contain a@gmail.comsuffix andhdis absent, Google is not
authoritative and password or other challenge methods are recommended to verify
the user.email_verifiedcan also be true as Google initially verified the
user when the Google account was created, however ownership of the third party
email account may have since changed.
Rather than writing your own code to perform these verification steps, we strongly
recommend using a Google API client library for your platform, or a general-purpose
JWT library. For development and debugging, you can call ourtokeninfovalidation endpoint.
importcom.google.api.client.googleapis.auth.oauth2.GoogleIdToken;importcom.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;importcom.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;...GoogleIdTokenVerifierverifier=newGoogleIdTokenVerifier.Builder(transport,jsonFactory)// Specify the WEB_CLIENT_ID of the app that accesses the backend:.setAudience(Collections.singletonList(WEB_CLIENT_ID))// Or, if multiple clients access the backend://.setAudience(Arrays.asList(WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3)).build();// (Receive idTokenString by HTTPS POST)GoogleIdTokenidToken=verifier.verify(idTokenString);if(idToken!=null){Payloadpayload=idToken.getPayload();// Print user identifier. This ID is unique to each Google Account, making it suitable for// use as a primary key during account lookup. Email is not a good choice because it can be// changed by the user.StringuserId=payload.getSubject();System.out.println("User ID: "+userId);// Get profile information from payloadStringemail=payload.getEmail();booleanemailVerified=Boolean.valueOf(payload.getEmailVerified());Stringname=(String)payload.get("name");StringpictureUrl=(String)payload.get("picture");Stringlocale=(String)payload.get("locale");StringfamilyName=(String)payload.get("family_name");StringgivenName=(String)payload.get("given_name");// Use or store profile information// ...}else{System.out.println("Invalid ID token.");}
TheGoogleIdTokenVerifier.verify()method verifies the JWT
signature, theaudclaim, theissclaim, and theexpclaim.
If you need to validate that the ID token represents a Google Workspace or Cloud
organization account, you can verify thehdclaim by checking the domain name
returned by thePayload.getHostedDomain()method. The domain of theemailclaim is insufficient to ensure that the account is managed by a domain
or organization.
Then, call theverifyIdToken()function. For example:
const{OAuth2Client}=require('google-auth-library');constclient=newOAuth2Client();asyncfunctionverify(){constticket=awaitclient.verifyIdToken({idToken:token,audience:WEB_CLIENT_ID,// Specify the WEB_CLIENT_ID of the app that accesses the backend// Or, if multiple clients access the backend://[WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3]});constpayload=ticket.getPayload();// This ID is unique to each Google Account, making it suitable for use as a primary key// during account lookup. Email is not a good choice because it can be changed by the user.constuserid=payload['sub'];// If the request specified a Google Workspace domain:// const domain = payload['hd'];}verify().catch(console.error);
TheverifyIdTokenfunction verifies
the JWT signature, theaudclaim, theexpclaim,
and theissclaim.
If you need to validate that the ID token represents a Google Workspace or Cloud
organization account, you can check thehdclaim, which indicates the hosted
domain of the user. This must be used when restricting access to a resource to only members
of certain domains. The absence of this claim indicates that the account does not belong to
a Google hosted domain.
Then, call theverifyIdToken()function. For example:
require_once 'vendor/autoload.php';// Get $id_token via HTTPS POST.$client = new Google_Client(['client_id' => $WEB_CLIENT_ID]); // Specify the WEB_CLIENT_ID of the app that accesses the backend$payload = $client->verifyIdToken($id_token);if ($payload) {// This ID is unique to each Google Account, making it suitable for use as a primary key// during account lookup. Email is not a good choice because it can be changed by the user.$userid = $payload['sub'];// If the request specified a Google Workspace domain//$domain = $payload['hd'];} else {// Invalid ID token}
TheverifyIdTokenfunction verifies
the JWT signature, theaudclaim, theexpclaim,
and theissclaim.
If you need to validate that the ID token represents a Google Workspace or Cloud
organization account, you can check thehdclaim, which indicates the hosted
domain of the user. This must be used when restricting access to a resource to only members
of certain domains. The absence of this claim indicates that the account does not belong to
a Google hosted domain.
Python
To validate an ID token in Python, use theverify_oauth2_tokenfunction. For example:
fromgoogle.oauth2importid_tokenfromgoogle.auth.transportimportrequests# (Receive token by HTTPS POST)# ...try:# Specify the WEB_CLIENT_ID of the app that accesses the backend:idinfo=id_token.verify_oauth2_token(token,requests.Request(),WEB_CLIENT_ID)# Or, if multiple clients access the backend server:# idinfo = id_token.verify_oauth2_token(token, requests.Request())# if idinfo['aud'] not in [WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3]:# raise ValueError('Could not verify audience.')# If the request specified a Google Workspace domain# if idinfo['hd'] != DOMAIN_NAME:# raise ValueError('Wrong domain name.')# ID token is valid. Get the user's Google Account ID from the decoded token.# This ID is unique to each Google Account, making it suitable for use as a primary key# during account lookup. Email is not a good choice because it can be changed by the user.userid=idinfo['sub']exceptValueError:# Invalid tokenpass
Theverify_oauth2_tokenfunction verifies the JWT
signature, theaudclaim, and theexpclaim.
You must also verify thehdclaim (if applicable) by examining the object thatverify_oauth2_tokenreturns. If multiple clients access the
backend server, also manually verify theaudclaim.
Once the token's validity is confirmed, you can use the information in
theGoogle ID tokento correlate the account status of your site:
An unregistered user:You can show a sign-up user interface
(UI) that allows the user to provide additional profile information, if
required. It also allows the user to silently create the new account and
a logged-in user session.
An existing account that already exists in your site:You can show a
web page that allows the end user to input their password and link the
legacy account with their Google credentials. This confirms that the
user has access to the existing account.
A returning federated user:You can silently sign the user in.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-12-22 UTC."],[],[]]