Firebase is back at Google I/O on May 14! Register now.
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/[email protected] |
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/[email protected]
and 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.
[{ "type": "thumb-down", "id": "missingTheInformationINeed", "label":"Missing the information I need" },{ "type": "thumb-down", "id": "tooComplicatedTooManySteps", "label":"Too complicated / too many steps" },{ "type": "thumb-down", "id": "outOfDate", "label":"Out of date" },{ "type": "thumb-down", "id": "samplesCodeIssue", "label":"Samples / code issue" },{ "type": "thumb-down", "id": "otherDown", "label":"Other" }] [{ "type": "thumb-up", "id": "easyToUnderstand", "label":"Easy to understand" },{ "type": "thumb-up", "id": "solvedMyProblem", "label":"Solved my problem" },{ "type": "thumb-up", "id": "otherUp", "label":"Other" }]