با مجموعهها، منظم بمانید
ذخیره و طبقهبندی محتوا براساس اولویتهای شما.
اگر برنامه مشتری Firebase شما با یک سرور باطن سفارشی ارتباط برقرار می کند، ممکن است لازم باشد کاربر وارد شده فعلی را در آن سرور شناسایی کنید. برای انجام این کار ایمن، پس از ورود موفقیت آمیز به سیستم، رمز ID کاربر را با استفاده از HTTPS به سرور خود ارسال کنید. سپس در سرور، یکپارچگی و اصالت توکن ID را بررسی کنید و uid از آن بازیابی کنید. می توانید از uid ارسال شده به این روش برای شناسایی ایمن کاربر وارد شده فعلی در سرور خود استفاده کنید.
قبل از شروع
برای تأیید رمزهای ID با Firebase Admin SDK، باید یک حساب سرویس داشته باشید. دستورالعملهای راهاندازی Admin SDK را برای اطلاعات بیشتر در مورد نحوه مقداردهی اولیه Admin SDK با یک حساب سرویس دنبال کنید.
بازیابی نشانه های ID در مشتریان
هنگامی که کاربر یا دستگاهی با موفقیت وارد سیستم میشود، Firebase یک کد ID مربوطه ایجاد میکند که به طور منحصربهفرد آنها را شناسایی میکند و به آنها اجازه دسترسی به چندین منبع، مانند Firebase Realtime Database و Cloud Storage را میدهد. میتوانید برای شناسایی کاربر یا دستگاه در سرور باطن سفارشی خود، از آن کد ID دوباره استفاده کنید. برای بازیابی رمز شناسه از مشتری، مطمئن شوید که کاربر وارد سیستم شده است و سپس رمز ID را از کاربر وارد شده دریافت کنید:
iOS+
هدف-C
FIRUser*currentUser=[FIRAuthauth].currentUser;[currentUsergetIDTokenForcingRefresh:YEScompletion:^(NSString*_NullableidToken,NSError*_Nullableerror){if(error){// Handle errorreturn;}// Send token to your backend via HTTPS// ...}];
سویفت
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// ...}
وب
firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
// Send token to your backend via HTTPS
// ...
}).catch(function(error) {
// Handle error
});
هنگامی که یک نشانه شناسه دارید، می توانید آن JSON Web Token (JWT) را به باطن خود ارسال کنید و با استفاده از Firebase Admin SDK یا با استفاده از کتابخانه JWT شخص ثالث اگر سرور شما به زبانی نوشته شده است که Firebase به طور بومی پشتیبانی نمی کند، آن را تأیید کنید.
با استفاده از Firebase Admin SDK، کدهای ID را تأیید کنید
Firebase Admin SDK دارای یک روش داخلی برای تأیید و رمزگشایی توکن های 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});
جاوا
// idToken comes from the client app (shown above)FirebaseTokendecodedToken=FirebaseAuth.getInstance().verifyIdToken(idToken);Stringuid=decodedToken.getUid();
پایتون
# id_token comes from the client app (shown above)decoded_token=auth.verify_id_token(id_token)uid=decoded_token['uid']
برو
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("Verified ID token: %v\n",token)
تأیید کد شناسه به شناسه پروژه نیاز دارد. Firebase Admin SDK تلاش می کند تا یک ID پروژه را از طریق یکی از روش های زیر بدست آورد:
اگر SDK با یک گزینه app explicit projectId مقداردهی اولیه شده باشد، SDK از مقدار آن گزینه استفاده می کند.
اگر SDK با اعتبار حساب سرویس راه اندازی شده باشد، SDK از فیلد project_id شیء JSON حساب سرویس استفاده می کند.
اگر متغیر محیطی GOOGLE_CLOUD_PROJECT تنظیم شده باشد، SDK از مقدار خود به عنوان شناسه پروژه استفاده می کند. این متغیر محیطی برای کدهای در حال اجرا در زیرساخت Google مانند App Engine و Compute Engine در دسترس است.
رمزهای ID را با استفاده از کتابخانه JWT شخص ثالث تأیید کنید
اگر پشتیبان شما به زبانی است که توسط Firebase Admin SDK پشتیبانی نمیشود، همچنان میتوانید نشانههای ID را تأیید کنید. ابتدا یک کتابخانه JWT شخص ثالث برای زبان خود پیدا کنید . سپس، هدر، بار و امضای شناسه را تأیید کنید.
بررسی کنید که هدر شناسه رمز با محدودیتهای زیر مطابقت دارد:
ادعاهای سرصفحه شناسه
alg
الگوریتم
"RS256"
kid
شناسه کلید
باید با یکی از کلیدهای عمومی فهرست شده در https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com مطابقت داشته باشد.
بررسی کنید که بار رمز شناسه با محدودیتهای زیر مطابقت دارد:
ادعاهای بارگیری رمز شناسه
exp
زمان انقضا
باید در آینده باشد. زمان از زمان یونیکس بر حسب ثانیه اندازه گیری می شود.
iat
صادر شده در زمان
باید در گذشته باشد. زمان از زمان یونیکس بر حسب ثانیه اندازه گیری می شود.
aud
مخاطب
باید شناسه پروژه Firebase شما باشد، شناسه منحصربهفرد پروژه Firebase شما، که میتوانید در URL کنسول آن پروژه پیدا کنید.
iss
صادر کننده
باید "https://securetoken.google.com/<projectId>" باشد، جایی که <projectId> همان شناسه پروژه مورد استفاده برای aud در بالا است.
sub
موضوع
باید یک رشته غیر خالی باشد و باید uid کاربر یا دستگاه باشد.
auth_time
زمان احراز هویت
باید در گذشته باشد. زمانی که کاربر احراز هویت کرد.
در نهایت، اطمینان حاصل کنید که رمز شناسایی توسط کلید خصوصی مربوط به ادعای kid نشانه امضا شده است. کلید عمومی را از https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com بگیرید و از کتابخانه JWT برای تأیید امضا استفاده کنید. از مقدار max-age در هدر Cache-Control پاسخ از آن نقطه پایانی استفاده کنید تا بدانید چه زمانی باید کلیدهای عمومی را بازخوانی کنید.
در صورت موفقیت آمیز بودن تمامی تاییدیه های فوق، می توانید از موضوع ( sub ) شناسه به عنوان uid کاربر یا دستگاه مربوطه استفاده کنید.
تاریخ آخرین بهروزرسانی 2025-08-28 بهوقت ساعت هماهنگ جهانی.
[[["درک آسان","easyToUnderstand","thumb-up"],["مشکلم را برطرف کرد","solvedMyProblem","thumb-up"],["غیره","otherUp","thumb-up"]],[["اطلاعاتی که نیاز دارم وجود ندارد","missingTheInformationINeed","thumb-down"],["بیشازحد پیچیده/ مراحل بسیار زیاد","tooComplicatedTooManySteps","thumb-down"],["قدیمی","outOfDate","thumb-down"],["مشکل ترجمه","translationIssue","thumb-down"],["مشکل کد / نمونهها","samplesCodeIssue","thumb-down"],["غیره","otherDown","thumb-down"]],["تاریخ آخرین بهروزرسانی 2025-08-28 بهوقت ساعت هماهنگ جهانی."],[],[],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\n[JSON Web Token (JWT)](https://www.jwt.io/introduction) to your backend and\nvalidate it using the Firebase Admin SDK, or using a third-party JWT library if\nyour server is written in a language which Firebase does not natively 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."]]