Verifying ID Tokens

If your Firebase client app communicates with a custom backend server, you might need to identify the currently signed-in user on that server. 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.

Before you begin

To verify ID tokens with the Firebase server SDKs, you must have a service account. Follow the server SDK setup instructions for more information on how to initialize your server SDK with a service account.

Retrieve ID tokens on clients

When a user or device successfully signs in, Firebase creates a corresponding ID token that uniquely identifies them and grants them access to several resources, such as Firebase Realtime Database and Firebase Storage. You can re-use that ID token to identify the user or device on your custom backend server. To retrieve the ID token from the client, make sure the user is signed in and then get the ID token from the signed-in user:

iOS

Objective-C

FIRUser *currentUser = [FIRAuth auth].currentUser;
[currentUser getTokenForcingRefresh: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()?.currentUser
currentUser?.getTokenForcingRefresh(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.getToken(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();
            }
        }
    });

Web

firebase.auth().currentUser.getToken(/* 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 validate it using one of the official Firebase server SDKs or using a third-party JWT library if your server is written in a language which Firebase does not natively support.

Verify ID tokens using the Firebase SDK

The Firebase server SDKs have a built-in method for verifying and decoding ID tokens. If the provided ID token has the correct format, is not expired, and is properly signed, the method returns the decoded ID token. You can grab the uid of the user or device from the decoded token.

Node.js

// idToken comes from the client app (shown above)

firebase.auth().verifyIdToken(idToken).then(function(decodedToken) {
  var uid = decodedToken.uid;
  // ...
}).catch(function(error) {
  // Handle error
});

Java

// idToken comes from the client app (shown above)

FirebaseAuth.getInstance().verifyIdToken(idToken)
    .addOnSuccessListener(new OnSuccessListener<FirebaseToken>() {
        @Override
        public void onSuccess(FirebaseToken decodedToken) {
            String uid = decodedToken.getUid();
            // ...
        }
});

Verify ID tokens using a third-party JWT library

If your backend is in a language that doesn't have an official Firebase server SDK, 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.

Finally, ensure that the ID token was signed by the private key corresponding to the token's kid claim. Grab the public key from https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com and use a JWT library to verify the signature. Use the value of max-age in the Cache-Control header of the response from that endpoint to know when to refresh 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.

Send feedback about...

Need help? Visit our support page.