当用户或设备成功登录后,Firebase 会创建一个相应的 ID 令牌以进行唯一标识,并向其授予多个资源(例如 Firebase Realtime Database 和 Cloud Storage)的访问权限。您还可以将该 ID 令牌用于标识自定义后端服务器上的用户或设备。如需从客户端检索 ID 令牌,请确保用户已登录,然后从已登录的用户处获取 ID 令牌:
iOS+
Objective-C
FIRUser*currentUser=[FIRAuthauth].currentUser;[currentUsergetIDTokenForcingRefresh:YEScompletion:^(NSString*_NullableidToken,NSError*_Nullableerror){if(error){// Handle errorreturn;}// Send token to your backend via HTTPS// ...}];
Swift
let currentUser = FIRAuth.auth()?.currentUser
currentUser?.getIDTokenForcingRefresh(true) { idToken, error in
if let error = error {
// Handle error
return;
}
// Send token to your backend via HTTPS
// ...
}
Firebase.Auth.FirebaseUseruser=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;}stringidToken=task.Result;// Send token to your backend via HTTPS
// ...});
C++
firebase::auth::Useruser=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
});
Firebase Admin SDK 内置了用于验证和解码 ID 令牌的方法。如果提供的 ID 令牌格式正确、未过期且经过正确签名,则该方法会返回已解码的 ID 令牌。您可以从已解码的令牌中获取用户或设备的 uid。
请按照 Admin SDK 安装说明,使用服务账号初始化 Admin SDK。然后,使用 verifyIdToken() 方法验证 ID 令牌:
Node.js
// idToken comes from the client appgetAuth().verifyIdToken(idToken).then((decodedToken)=>{constuid=decodedToken.uid;// ...}).catch((error)=>{// Handle error});
Java
// idToken comes from the client app (shown above)FirebaseTokendecodedToken=FirebaseAuth.getInstance().verifyIdToken(idToken);Stringuid=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)iferr!=nil{log.Fatalf("error getting Auth client: %v\n",err)}token,err:=client.VerifyIDToken(ctx,idToken)iferr!=nil{log.Fatalf("error verifying ID token: %v\n",err)}log.Printf("Verifie
[null,null,["最后更新时间 (UTC):2025-08-14。"],[],[],null,["\u003cbr /\u003e\n\nIf your Firebase client app communicates with a custom backend server, you\nmight need to identify the currently signed-in user on that server. To do so\nsecurely, after a successful sign-in, send the user's ID token to your server\nusing HTTPS. Then, on the server, verify the integrity and authenticity of the\nID token and retrieve the `uid` from it. You can use the `uid` transmitted in\nthis way to securely identify the currently signed-in user on your server.\n| **Note:** Many use cases for verifying ID tokens on the server can be accomplished by using Security Rules for the [Firebase Realtime Database](/docs/database/security) and [Cloud Storage](/docs/storage/security). See if those solve your problem before verifying ID tokens yourself.\n| **Warning:** The ID token verification methods included in the Firebase Admin SDKs are meant to verify ID tokens that come from the client SDKs, not the custom tokens that you create with the Admin SDKs. See [Auth tokens](/docs/auth/users#auth_tokens) for more information.\n\nBefore you begin\n\nTo verify ID tokens with the Firebase Admin SDK, you must have a service\naccount. Follow the [Admin SDK setup instructions](/docs/admin/setup) for\nmore information on how to initialize the Admin SDK with a service account.\n\nRetrieve ID tokens on clients\n\nWhen a user or device successfully signs in, Firebase creates a corresponding\nID token that uniquely identifies them and grants them access to several\nresources, such as Firebase Realtime Database and Cloud Storage. You can\nre-use that ID token to identify the user or device on your custom backend\nserver. To retrieve the ID token from the client, make sure the user is signed\nin and then get the ID token from the signed-in user: \n\niOS+\n\nObjective-C \n\n FIRUser *currentUser = [FIRAuth auth].currentUser;\n [currentUser getIDTokenForcingRefresh:YES\n completion:^(NSString *_Nullable idToken,\n NSError *_Nullable error) {\n if (error) {\n // Handle error\n return;\n }\n\n // Send token to your backend via HTTPS\n // ...\n }];\n\nSwift \n\n let currentUser = FIRAuth.auth()?.currentUser\n currentUser?.getIDTokenForcingRefresh(true) { idToken, error in\n if let error = error {\n // Handle error\n return;\n }\n\n // Send token to your backend via HTTPS\n // ...\n }\n\nAndroid \n\n FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();\n mUser.getIdToken(true)\n .addOnCompleteListener(new OnCompleteListener\u003cGetTokenResult\u003e() {\n public void onComplete(@NonNull Task\u003cGetTokenResult\u003e task) {\n if (task.isSuccessful()) {\n String idToken = task.getResult().getToken();\n // Send token to your backend via HTTPS\n // ...\n } else {\n // Handle error -\u003e task.getException();\n }\n }\n });\n\nUnity \n\n Firebase.Auth.FirebaseUser user = auth.CurrentUser;\n user.TokenAsync(true).ContinueWith(task =\u003e {\n if (task.IsCanceled) {\n Debug.LogError(\"TokenAsync was canceled.\");\n return;\n }\n\n if (task.IsFaulted) {\n Debug.LogError(\"TokenAsync encountered an error: \" + task.Exception);\n return;\n }\n\n string idToken = task.Result;\n\n // Send token to your backend via HTTPS\n // ...\n });\n\nC++ \n\n firebase::auth::User user = auth-\u003ecurrent_user();\n if (user.is_valid()) {\n firebase::Future\u003cstd::string\u003e idToken = user.GetToken(true);\n\n // Send token to your backend via HTTPS\n // ...\n }\n\nWeb \n\n firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {\n // Send token to your backend via HTTPS\n // ...\n }).catch(function(error) {\n // Handle error\n });\n\nOnce you have an ID token, you can send that JWT to your backend and validate\nit using the Firebase Admin SDK, or using a third-party JWT\nlibrary if your server is written in a language which Firebase does not\nnatively support.\n\nVerify ID tokens using the Firebase Admin SDK\n\nThe Firebase Admin SDK has a built-in method for verifying and decoding ID\ntokens. If the provided ID token has the correct format, is not expired, and is\nproperly signed, the method returns the decoded ID token. You can grab the\n`uid` of the user or device from the decoded token.\n| **Note:** This does not check whether or not the token has been revoked. See: [Detect ID token revocation](/docs/auth/admin/manage-sessions#detect_id_token_revocation).\n\nFollow the [Admin SDK setup instructions](/docs/admin/setup) to initialize\nthe Admin SDK with a service account. Then, use the `verifyIdToken()` method\nto verify an ID token: \n\nNode.js \n\n // idToken comes from the client app\n getAuth()\n .verifyIdToken(idToken)\n .then((decodedToken) =\u003e {\n const uid = decodedToken.uid;\n // ...\n })\n .catch((error) =\u003e {\n // Handle error\n });\n\nJava \n\n // idToken comes from the client app (shown above)\n FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdToken(idToken);\n String uid = decodedToken.getUid();\n\nPython \n\n # id_token comes from the client app (shown above)\n\n decoded_token = auth.verify_id_token(id_token)\n uid = decoded_token['uid']\n\nGo \n\n client, err := app.Auth(ctx)\n if err != nil {\n \tlog.Fatalf(\"error getting Auth client: %v\\n\", err)\n }\n\n token, err := client.VerifyIDToken(ctx, idToken)\n if err != nil {\n \tlog.Fatalf(\"error verifying ID token: %v\\n\", err)\n }\n\n log.Printf(\"Verified ID token: %v\\n\", token) \n https://github.com/firebase/firebase-admin-go/blob/26dec0b7589ef7641eefd6681981024079b8524c/snippets/auth.go#L82-L92\n\nC# \n\n FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance\n .VerifyIdTokenAsync(idToken);\n string uid = decodedToken.Uid;\n\nID token verification requires a project ID. The Firebase Admin SDK attempts\nto obtain a project ID via one of the following methods:\n\n- If the SDK was initialized with an explicit `projectId` app option, the SDK uses the value of that option.\n- If the SDK was initialized with service account credentials, the SDK uses the `project_id` field of the service account JSON object.\n- If the `GOOGLE_CLOUD_PROJECT` environment variable is set, the SDK uses its value as the project ID. This environment variable is available for code running on Google infrastructure such as App Engine and Compute Engine.\n\nVerify ID tokens using a third-party JWT library\n\nIf your backend is in a language not supported by the Firebase Admin\nSDK, you can still verify ID tokens. First,\n[find a third-party JWT library for your language](https://jwt.io/). Then,\nverify the header, payload, and signature of the ID token.\n\nVerify the ID token's header conforms to the following constraints:\n\n| ID Token Header Claims |||\n|-------|-----------|------------------------------------------------------------------------------------------------------------------------------------------------|\n| `alg` | Algorithm | `\"RS256\"` |\n| `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` |\n\nVerify the ID token's payload conforms to the following constraints:\n\n| ID Token Payload Claims |||\n|-------------|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------|\n| `exp` | Expiration time | Must be in the future. The time is measured in seconds since the UNIX epoch. |\n| `iat` | Issued-at time | Must be in the past. The time is measured in seconds since the UNIX epoch. |\n| `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. |\n| `iss` | Issuer | Must be `\"https://securetoken.google.com/\u003cprojectId\u003e\"`, where `\u003cprojectId\u003e` is the same project ID used for `aud` above. |\n| `sub` | Subject | Must be a non-empty string and must be the `uid` of the user or device. |\n| `auth_time` | Authentication time | Must be in the past. The time when the user authenticated. |\n\nFinally, ensure that the ID token was signed by the private key corresponding\nto the token's `kid` claim. Grab the public key from\n`https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com`\nand use a JWT library to verify the signature. Use the value of `max-age` in\nthe `Cache-Control` header of the response from that endpoint to know when to\nrefresh the public keys.\n\nIf all the above verifications are successful, you can use the subject (`sub`)\nof the ID token as the `uid` of the corresponding user or device."]]