Verify ID Tokens  |  Firebase Authentication (2024)

Firebase is back at Google I/O on May 14! Register now.

Stay organized with collections Save and categorize content based on your preferences.

If your Firebase client app communicates with a custom backend server, youmight need to identify the currently signed-in user on that server. To do sosecurely, after a successful sign-in, send the user's ID token to your serverusing HTTPS. Then, on the server, verify the integrity and authenticity of theID token and retrieve the uid from it. You can use the uid transmitted inthis way to securely identify the currently signed-in user on your server.

Before you begin

To verify ID tokens with the Firebase Admin SDK, you must have a serviceaccount. Follow the Admin SDK setup instructions formore information on how to initialize the Admin SDK with a service account.

Retrieve ID tokens on clients

When a user or device successfully signs in, Firebase creates a correspondingID token that uniquely identifies them and grants them access to severalresources, such as Firebase Realtime Database and Cloud Storage. You canre-use that ID token to identify the user or device on your custom backendserver. To retrieve the ID token from the client, make sure the user is signedin and then get the ID token from the signed-in user:

iOS+

Objective-C
FIRUser *currentUser = [FIRAuth auth].currentUser;[currentUser getIDTokenForcingRefresh:YES completion:^(NSString *_Nullable idToken, NSError *_Nullable error) { if (error) { // Handle error return; } // Send token to your backend via HTTPS // ...}];
Swift
let currentUser = FIRAuth.auth()?.currentUsercurrentUser?.getIDTokenForcingRefresh(true) { idToken, error in if let error = error { // Handle error return; } // Send token to your backend via HTTPS // ...}

Android

FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();mUser.getIdToken(true) .addOnCompleteListener(new OnCompleteListener<GetTokenResult>() { public void onComplete(@NonNull Task<GetTokenResult> task) { if (task.isSuccessful()) { String idToken = task.getResult().getToken(); // Send token to your backend via HTTPS // ... } else { // Handle error -> task.getException(); } } });

Unity

Firebase.Auth.FirebaseUser user = auth.CurrentUser;user.TokenAsync(true).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("TokenAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("TokenAsync encountered an error: " + task.Exception); return; } string idToken = task.Result; // Send token to your backend via HTTPS // ...});

C++

firebase::auth::User user = auth->current_user();if (user.is_valid()) { firebase::Future<std::string> idToken = user.GetToken(true); // Send token to your backend via HTTPS // ...}

Web

firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) { // Send token to your backend via HTTPS // ...}).catch(function(error) { // Handle error});

Once you have an ID token, you can send that JWT to your backend and validateit using the Firebase Admin SDK, or using a third-party JWTlibrary if your server is written in a language which Firebase does notnatively support.

Verify ID tokens using the Firebase Admin SDK

The Firebase Admin SDK has a built-in method for verifying and decoding IDtokens. If the provided ID token has the correct format, is not expired, and isproperly signed, the method returns the decoded ID token. You can grab theuid of the user or device from the decoded token.

Follow the Admin SDK setup instructions to initializethe Admin SDK with a service account. Then, use the verifyIdToken() methodto verify an ID token:

Node.js

// idToken comes from the client appgetAuth() .verifyIdToken(idToken) .then((decodedToken) => { const uid = decodedToken.uid; // ... }) .catch((error) => { // Handle error });

Java

// idToken comes from the client app (shown above)FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdToken(idToken);String uid = decodedToken.getUid();

Python

# id_token comes from the client app (shown above)decoded_token = auth.verify_id_token(id_token)uid = decoded_token['uid']

Go

client, err := app.Auth(ctx)if err != nil {log.Fatalf("error getting Auth client: %v\n", err)}token, err := client.VerifyIDToken(ctx, idToken)if err != nil {log.Fatalf("error verifying ID token: %v\n", err)}log.Printf("Verified ID token: %v\n", token)

C#

FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance .VerifyIdTokenAsync(idToken);string uid = decodedToken.Uid;

ID token verification requires a project ID. The Firebase Admin SDK attemptsto obtain a project ID via one of the following methods:

  • If the SDK was initialized with an explicit projectId app option, theSDK uses the value of that option.
  • If the SDK was initialized with service account credentials, the SDK usesthe project_id field of the service account JSON object.
  • If the GOOGLE_CLOUD_PROJECT environment variable is set, the SDK usesits value as the project ID. This environment variable is available forcode running on Google infrastructure such as App Engine andCompute Engine.

Verify ID tokens using a third-party JWT library

If your backend is in a language not supported by the Firebase AdminSDK, you can still verify ID tokens. First,find a third-party JWT library for your language. Then,verify the header, payload, and signature of the ID token.

Verify the ID token's header conforms to the following constraints:

ID Token Header Claims
alg Algorithm "RS256"
kid Key ID Must correspond to one of the public keys listed at https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com

Verify the ID token's payload conforms to the following constraints:

ID Token Payload Claims
exp Expiration time Must be in the future. The time is measured in seconds since the UNIX epoch.
iat Issued-at time Must be in the past. The time is measured in seconds since the UNIX epoch.
aud Audience Must be your Firebase project ID, the unique identifier for your Firebase project, which can be found in the URL of that project's console.
iss Issuer Must be "https://securetoken.google.com/<projectId>", where <projectId> is the same project ID used for aud above.
sub Subject Must be a non-empty string and must be the uid of the user or device.
auth_time Authentication time Must be in the past. The time when the user authenticated.

Finally, ensure that the ID token was signed by the private key correspondingto the token's kid claim. Grab the public key fromhttps://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.comand use a JWT library to verify the signature. Use the value of max-age inthe Cache-Control header of the response from that endpoint to know when torefresh the public keys.

If all the above verifications are successful, you can use the subject (sub)of the ID token as the uid of the corresponding user or device.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-04-16 UTC.

Verify ID Tokens  |  Firebase Authentication (2024)

FAQs

How to get ID token? ›

Get an ID token from the credentials object

After you retrieve a user's credentials, check if the credentials object includes an ID token. If it does, send it to your backend.

How to get ID token from Access Token Google? ›

Methods for getting an ID token
  1. Get an ID token from the metadata server.
  2. Use a connecting service to generate an ID token.
  3. Generate an ID token by impersonating a service account.
  4. Generate a generic ID token for development with Cloud Run and Cloud Functions.
  5. Generate an ID token using an external identity provider.

How to check if token is valid in Firebase? ›

To do so securely, after a successful sign-in, send the user's ID token to your server using HTTPS. Then, on the server, verify the integrity and authenticity of the ID token and retrieve the uid from it. You can use the uid transmitted in this way to securely identify the currently signed-in user on your server.

How to verify Firebase custom token? ›

  1. Verify the App Check token's signature to ensure it is legitimate.
  2. Ensure that the token's header uses the algorithm RS256.
  3. Ensure that the token's header has type JWT.
  4. Ensure that the token is issued by Firebase App Check under your project.
  5. Ensure that the token has not expired.

How to verify an auth token? ›

You can validate your tokens locally by parsing the token, verifying the token signature, and validating the claims that are stored in the token. Parse the tokens. The JSON Web Token (JWT) is a standard way of securely passing information. It consists of three main parts: Header, Payload, and Signature.

How do I get token authentication? ›

Token Authentication in 4 Easy Steps
  1. Request: The person asks for access to a server or protected resource. ...
  2. Verification: The server determines that the person should have access. ...
  3. Tokens: The server communicates with the authentication device, like a ring, key, phone, or similar device.
Feb 28, 2024

How is an ID token validated? ›

The ID token is properly signed by Google. Use Google's public keys (available in JWK or PEM format) to verify the token's signature. These keys are regularly rotated; examine the Cache-Control header in the response to determine when you should retrieve them again.

What is the difference between ID token and access token? ›

ID Tokens are JSON Web Tokens (JWT) that contain claims about a user's identity, such as their username, email, etc. Access Tokens are used to grant applications permission to access server resources on behalf of the user.

How do I get my access token? ›

Page access tokens are used in Graph API calls to manage Facebook Pages. To generate a page access token, an admin of the page must grant your app the Page permission or permissions needed. Once granted, you can retrieve the Page access token using a user access token with the required permissions.

How long is a Google ID token valid? ›

ID tokens are valid for up to 1 hour (3,600 seconds).

How do I refresh my Google ID token? ›

You can refresh an Identity Platform ID token by issuing an HTTP POST request to the securetoken.googleapis.com endpoint. Note: By default, Google validates the project number of your refresh token to ensure it matches that of your API key.

Does an ID token expire? ›

ID token lifetime

By default, an ID token is valid for 36000 seconds (10 hours). If there are security concerns, you can shorten the time period before the token expires, keeping in mind that one of the purposes of the token is to improve user experience by caching user information.

How to get ID token from Firebase? ›

Use the appropriate Firebase Auth client library to get an ID token:
  1. Android: Use the GetTokenResult(). getToken() method.
  2. iOS: Use the User. getIDTokenResult(completion:) method.
  3. Web: Use the firebase. User. getIdToken() method.

How long is Firebase ID token valid? ›

Firebase ID tokens are short lived and last for an hour; the refresh token can be used to retrieve new ID tokens. Refresh tokens expire only when one of the following occurs: The user is deleted. The user is disabled.

How do I authorize with Firebase authentication? ›

If you need to authorize the user, you have to add a user list to the database and tie it together with a cloud function. When the Firebase Auth entry it is created or updated, it could trigger a cloud function (CF). This CF can access the user list you have available in the database and give access to the user.

Where can I find my token ID? ›

Token ID can be found in the Preferences page on the API tokens tab below the name which you have defined during the token creation process (see token creation docs).

What is the ID token code? ›

ID tokens are used in token-based authentication to cache user profile information and provide it to a client application, thereby providing better performance and experience.

What is a token ID number? ›

An ID Token is a type of security token used primarily in identity confirmation. Typically formatted as a JSON Web Token (JWT), it contains authenticated user profile information. When a user logs in via an authentication process like OpenID Connect (OIDC), they receive an ID token alongside an access token.

Top Articles
Latest Posts
Article information

Author: Van Hayes

Last Updated:

Views: 5570

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Van Hayes

Birthday: 1994-06-07

Address: 2004 Kling Rapid, New Destiny, MT 64658-2367

Phone: +512425013758

Job: National Farming Director

Hobby: Reading, Polo, Genealogy, amateur radio, Scouting, Stand-up comedy, Cryptography

Introduction: My name is Van Hayes, I am a thankful, friendly, smiling, calm, powerful, fine, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.