تنظيم صفحاتك في مجموعات
يمكنك حفظ المحتوى وتصنيفه حسب إعداداتك المفضّلة.
إذا كان تطبيق العميل على Firebase يتواصل مع خادم خلفي مخصّص، قد تحتاج إلى تحديد المستخدم الذي سجّل الدخول حاليًا على هذا الخادم. لإجراء ذلك بشكل آمن، أرسِل الرمز المميّز لتعريف المستخدم إلى الخادم بعد تسجيل الدخول بنجاح باستخدام HTTPS. بعد ذلك، تحقَّق على الخادم من سلامة رمز التعريف وصحته، واستردّ uid منه. يمكنك استخدام uid المُرسَل بهذه الطريقة لتحديد هوية المستخدم الذي سجّل الدخول حاليًا على خادمك بأمان.
قبل البدء
لإثبات صحة رموز التعريف باستخدام حزمة تطوير البرامج (SDK) الخاصة بمشرفي Firebase، يجب أن يكون لديك حساب خدمة. اتّبِع تعليمات إعداد حزمة SDK للمشرف لمعرفة المزيد من المعلومات حول كيفية إعداد حزمة SDK للمشرف باستخدام حساب خدمة.
استرداد رموز التعريف على الأجهزة
عندما يسجّل مستخدم أو جهاز الدخول بنجاح، ينشئ Firebase رمزًا مميّزًا للمعرّف المقابل يحدّد هويته بشكل فريد ويمنحه إذن الوصول إلى العديد من الموارد، مثل Firebase Realtime Database وCloud Storage. يمكنك إعادة استخدام رمز التعريف المميز هذا للتعرّف على المستخدم أو الجهاز على خادم الخلفية المخصّص. لاسترداد الرمز المميّز للمعرّف من العميل، تأكَّد من تسجيل دخول المستخدم، ثم احصل على الرمز المميّز للمعرّف من المستخدم الذي سجّل الدخول:
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// ...}
الويب
firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
// Send token to your backend via HTTPS
// ...
}).catch(function(error) {
// Handle error
});
بعد الحصول على رمز مميّز للمعرّف، يمكنك إرسال رمز JSON المميّز للويب (JWT) إلى الخلفية والتحقّق من صحته باستخدام حزمة تطوير البرامج (SDK) الخاصة بخدمة Firebase Admin، أو باستخدام مكتبة رموز JWT تابعة لجهة خارجية إذا كان الخادم مكتوبًا بلغة لا تتوافق مع Firebase بشكلٍ أصلي.
التحقّق من صحة رموز التعريف باستخدام حزمة تطوير البرامج (SDK) الخاصة بمدير Firebase
تتضمّن حزمة تطوير البرامج (SDK) الخاصة بمدير Firebase طريقة مدمجة للتحقّق من رموز التعريف المميزة وفك تشفيرها. إذا كان الرمز المميّز للمعرّف المقدَّم بالتنسيق الصحيح ولم تنتهِ صلاحيته وتم توقيعه بشكل صحيح، ستعرض الطريقة الرمز المميّز للمعرّف الذي تم فك ترميزه. يمكنك الحصول على
uid للمستخدم أو الجهاز من الرمز المميّز الذي تم فك ترميزه.
// 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("Verified ID token: %v\n",token)
يتطلّب إثبات صحة الرمز المميّز للمعرّف توفّر رقم تعريف المشروع. تحاول حزمة تطوير البرامج (SDK) الخاصة بمسؤولي Firebase الحصول على رقم تعريف المشروع بإحدى الطرق التالية:
إذا تمّت تهيئة حزمة SDK باستخدام خيار تطبيق projectId صريح، تستخدم حزمة SDK قيمة هذا الخيار.
إذا تمّت تهيئة حزمة تطوير البرامج (SDK) باستخدام بيانات اعتماد حساب الخدمة، ستستخدم حزمة تطوير البرامج (SDK) الحقل project_id لكائن JSON الخاص بحساب الخدمة.
في حال ضبط متغيّر البيئة GOOGLE_CLOUD_PROJECT، تستخدِم حزمة SDK قيمته كرقم تعريف المشروع. متغيّر البيئة هذا متاح للرموز التي يتم تشغيلها على بنية Google التحتية، مثل App Engine وCompute Engine.
التحقّق من صحة رموز التعريف باستخدام مكتبة JWT تابعة لجهة خارجية
إذا كانت الخلفية بلغة غير متوافقة مع حزمة تطوير البرامج (SDK) الخاصة بـ Firebase Admin، سيظل بإمكانك إثبات صحة رموز التعريف. أولاً، ابحث عن مكتبة JWT تابعة لجهة خارجية للغتك. بعد ذلك،
تحقَّق من العنوان والحمولة والتوقيع الخاص برمز التعريف.
تأكَّد من أنّ عنوان رمز التعريف يستوفي القيود التالية:
مطالبات عنوان رمز التعريف
alg
خوارزمية
"RS256"
kid
معرّف المفتاح
يجب أن يتوافق مع أحد المفاتيح العامة المدرَجة في
https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com
تأكَّد من أنّ حمولة رمز التعريف المميز تتوافق مع القيود التالية:
مطالبات حمولة الرمز المميز لبطاقة التعريف
exp
وقت انتهاء الصلاحية
يجب أن يكون في المستقبل. ويتم قياس الوقت بالثواني منذ بدء حساب الفترة في نظام التشغيل UNIX.
iat
وقت الإصدار
يجب أن يكون التاريخ في الماضي. ويتم قياس الوقت بالثواني منذ بدء حساب الفترة في نظام التشغيل UNIX.
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-09-05 (حسب التوقيت العالمي المتفَّق عليه)
[[["يسهُل فهم المحتوى.","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-09-05 (حسب التوقيت العالمي المتفَّق عليه)"],[],[],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."]]