אימות באמצעות Microsoft ו-C++
קל לארגן דפים בעזרת אוספים
אפשר לשמור ולסווג תוכן על סמך ההעדפות שלך.
אתם יכולים לאפשר למשתמשים לבצע אימות ב-Firebase באמצעות ספקי OAuth כמו Microsoft Azure Active Directory. לשם כך, משלבים באפליקציה כניסה גנרית מבוססת-אינטרנט באמצעות OAuth באמצעות Firebase SDK כדי לבצע את תהליך הכניסה מקצה לקצה.
התהליך הזה מחייב שימוש ב-Firebase SDK לנייד, ולכן הוא נתמך רק בפלטפורמות Android ו-Apple.
לפני שמתחילים
- מוסיפים את Firebase לפרויקט C++.
- במסוף Firebase, פותחים את הקטע אימות.
- בכרטיסייה Sign in method, מפעילים את הספק Microsoft.
- מוסיפים את מזהה הלקוח ואת סוד הלקוח ממסוף הפיתוח של הספק להגדרות הספק:
- כדי לרשום לקוח OAuth של Microsoft, פועלים לפי ההוראות במאמר תחילת העבודה: רישום אפליקציה בנקודת הקצה של Azure Active Directory v2.0.
חשוב לשים לב שנקודת הקצה הזו תומכת בכניסה באמצעות חשבונות Microsoft לשימוש אישי וגם באמצעות Azure
חשבונות Active Directory.
מידע נוסף על Azure Active Directory v2.0
- כשרושמים אפליקציות אצל הספקים האלה, חשוב לרשום את הדומיין
*.firebaseapp.com
של הפרויקט כדומיין להפניה אוטומטית של האפליקציה.
- לוחצים על שמירה.
גישה לכיתה firebase::auth::Auth
המחלקה
Auth
היא השער לכל הקריאות ל-API.
- מוסיפים את קובצי הכותרות של Auth ו-App:
#include "firebase/app.h"
#include "firebase/auth.h"
- בקוד האתחול, יוצרים
firebase::App
.
#if defined(__ANDROID__)
firebase::App* app =
firebase::App::Create(firebase::AppOptions(), my_jni_env, my_activity);
#else
firebase::App* app = firebase::App::Create(firebase::AppOptions());
#endif // defined(__ANDROID__)
- עליך לרכוש את הכיתה
firebase::auth::Auth
ל-firebase::App
.
יש מיפוי אחד לאחד בין App
לבין Auth
.
firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app);
טיפול בתהליך הכניסה באמצעות Firebase SDK
כדי לטפל בתהליך הכניסה באמצעות Firebase SDK:
בנייה של מופע של FederatedOAuthProviderData
שהוגדר באמצעות
מזהה הספק שמתאים ל-Microsoft.
firebase::auth::FederatedOAuthProviderData
provider_data(firebase::auth::MicrosoftAuthProvider::kProviderId);
אופציונלי: מציינים פרמטרים מותאמים אישית נוספים של OAuth שרוצים להגדיר
שליחה עם בקשת ה-OAuth.
// Prompt user to re-authenticate to Microsoft.
provider_data.custom_parameters["prompt"] = "login";
// Target specific email with login hint.
provider_data.custom_parameters["login_hint"] =
"user@firstadd.onmicrosoft.com";
למידע על הפרמטרים שנתמכים ב-Microsoft, ראו
מסמכי תיעוד של Microsoft OAuth.
שימו לב שאי אפשר להעביר פרמטרים שנדרשים ל-Firebase עם
setCustomParameters()
הפרמטרים האלה הם client_id, response_type, redirect_uri, state, scope ו-response_mode.
כדי לאפשר רק למשתמשים מדייר מסוים ב-Azure AD להיכנס לאפליקציה, אפשר להשתמש בשם הדומיין הידידותי של הדייר ב-Azure AD או במזהה ה-GUID של הדייר. כדי לעשות זאת, אפשר לציין
ה-"tenant" באובייקט של הפרמטרים המותאמים אישית.
// Optional "tenant" parameter in case you are using an Azure AD tenant.
// eg. '8eaef023-2b34-4da1-9baa-8bc8c9d6a490' or 'contoso.onmicrosoft.com'
// or "common" for tenant-independent tokens.
// The default value is "common".
provider_data.custom_parameters["tenant"] ="TENANT_ID";
אופציונלי: מציינים היקפי הרשאות נוספים של OAuth 2.0, מעבר לפרופיל הבסיסי, שרוצים לבקש מספק האימות.
provider_data.scopes.push_back("mail.read");
provider_data.scopes.push_back("calendars.read");
מידע נוסף זמין
מסמכי בנושא הרשאות והסכמה של Microsoft.
אחרי שהגדרתם את נתוני הספק, השתמשו בהם כדי ליצור
FederatedOAuthProvider
// Construct a FederatedOAuthProvider for use in Auth methods.
firebase::auth::FederatedOAuthProvider provider(provider_data);
מבצעים אימות עם Firebase באמצעות אובייקט של ספק האימות. חשוב לזכור שבניגוד לפעולות אחרות של FirebaseAuth, הפעולה הזו תשלוט בממשק המשתמש על ידי הצגת תצוגת אינטרנט שבה המשתמש יכול להזין את פרטי הכניסה שלו.
כדי להתחיל את תהליך הכניסה, צריך לקרוא ל-SignInWithProvider
:
firebase::Future<firebase::auth::AuthResult> result =
auth->SignInWithProvider(provider_data);
לאחר מכן הבקשה עשויה להמתין או
רישום קריאה חוזרת (callback) לגבי העתיד.
באמצעות אסימון הגישה של OAuth, אפשר לקרוא ל-
Microsoft Graph API.
בניגוד לספקים אחרים שנתמכים על ידי Firebase Auth, Microsoft לא
מספקים כתובת URL של תמונה, ובמקום זאת, הנתונים הבינאריים של תמונת פרופיל
לשליחת בקשה דרך
Microsoft Graph API.
הדוגמאות שלמעלה מתמקדות בתהליכי כניסה, אבל אפשר גם לקשר ספק של Microsoft Azure Active Directory למשתמש קיים באמצעות LinkWithProvider
. לדוגמה, אפשר לקשר כמה ספקים לאותו משתמש ולאפשר לו להיכנס באמצעות כל אחד מהם.
firebase::Future<firebase::auth::AuthResult> result = user.LinkWithProvider(provider_data);
אפשר להשתמש באותו קו ביטול נעילה יחד עם ReauthenticateWithProvider
, שיכול להיות
משמש לאחזור פרטי כניסה חדשים לפעולות רגישות שמצריכות
ההתחברות האחרונה.
firebase::Future<firebase::auth::AuthResult> result =
user.ReauthenticateWithProvider(provider_data);
לאחר מכן האפליקציה עשויה להמתין או לרשום התקשרות חזרה במכשיר
העתיד.
מתקדם: טיפול בתהליך הכניסה באופן ידני
בניגוד לספקי OAuth אחרים שנתמכים על ידי Firebase, כמו Google, Facebook,
וב-Twitter, שבהם אפשר להיכנס ישירות לחשבון באמצעות אסימון גישה ל-OAuth
שמבוססים על פרטי כניסה, אימות Firebase לא תומך באותה יכולת עבור
כמו Microsoft בגלל חוסר היכולת של Firebase
שרת לאימות לצורך אימות הקהל של אסימוני הגישה של Microsoft OAuth.
זוהי דרישת אבטחה קריטית שעלולה לחשוף אפליקציות
אתרים להעברה חוזרת של מתקפות שבהן התקבל אסימון גישה של Microsoft OAuth עבור
אפשר להשתמש בפרויקט אחד (תוקפים) כדי להיכנס לפרויקט אחר (קורבן).
במקום זאת, Firebase Auth מאפשר לטפל בכל תהליך OAuth
החלפה של קוד ההרשאה באמצעות מזהה וסוד הלקוח של OAuth
שהוגדר במסוף Firebase. מכיוון שאפשר להשתמש בקוד ההרשאה רק בשילוב עם מזהה לקוח או סוד לקוח ספציפיים, אי אפשר להשתמש בקוד הרשאה שהתקבל לפרויקט אחד בפרויקט אחר.
אם צריך להשתמש בספקים האלה בסביבות שלא נתמכות, צריך להשתמש בספריית OAuth של צד שלישי ובאימות מותאם אישית של Firebase. ההגדרה הראשונה נדרשת כדי לבצע אימות מול הספק
וגם כדי להחליף את פרטי הכניסה של הספק באסימון מותאם אישית.
השלבים הבאים
אחרי שמשתמש נכנס לחשבון בפעם הראשונה, נוצר חשבון משתמש חדש שמקושר לפרטי הכניסה – כלומר שם המשתמש והסיסמה, מספר הטלפון או פרטי ספק האימות – שבאמצעותם המשתמש נכנס לחשבון. החשבון החדש הזה מאוחסן כחלק מפרויקט Firebase, וניתן להשתמש בו כדי לזהות משתמש בכל האפליקציות בפרויקט, ללא קשר לאופן שבו המשתמש נכנס לחשבון.
-
באפליקציות שלכם, תוכלו לקבל את פרטי הפרופיל הבסיסיים של המשתמש דרך
אובייקט firebase::auth::User
:
firebase::auth::User user = auth->current_user();
if (user.is_valid()) {
std::string name = user.display_name();
std::string email = user.email();
std::string photo_url = user.photo_url();
// The user's ID, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server,
// if you have one. Use firebase::auth::User::Token() instead.
std::string uid = user.uid();
}
בכללי האבטחה של Firebase Realtime Database ו-Cloud Storage, אפשר לקבל את מזהה המשתמש הייחודי של המשתמש שנכנס לחשבון מהמשתנה auth
, ולהשתמש בו כדי לקבוע לאילו נתונים למשתמש תהיה גישה.
כדי לאפשר למשתמשים להיכנס לאפליקציה באמצעות כמה ספקי אימות, אפשר לקשר את פרטי הכניסה של ספק האימות לחשבון משתמש קיים.
כדי להוציא משתמש, קוראים לפונקציה
SignOut()
:
auth->SignOut();
אלא אם צוין אחרת, התוכן של דף זה הוא ברישיון Creative Commons Attribution 4.0 ודוגמאות הקוד הן ברישיון Apache 2.0. לפרטים, ניתן לעיין במדיניות האתר Google Developers. Java הוא סימן מסחרי רשום של חברת Oracle ו/או של השותפים העצמאיים שלה.
עדכון אחרון: 2025-08-16 (שעון UTC).
[null,null,["עדכון אחרון: 2025-08-16 (שעון UTC)."],[],[],null,["You can let your users authenticate with Firebase using OAuth providers like\nMicrosoft Azure Active Directory by integrating web-based generic OAuth Login\ninto your app using the Firebase SDK to carry out the end to end sign-in flow.\nSince this flow requires the use of the phone-based Firebase SDKs, it is only\nsupported on Android and Apple platforms.\n\nBefore you begin\n\n1. [Add Firebase to your C++ project](/docs/cpp/setup#note_select_platform).\n2. In the [Firebase console](//console.firebase.google.com/), open the **Auth** section.\n3. On the **Sign in method** tab, enable the **Microsoft** provider.\n4. Add the **Client ID** and **Client Secret** from that provider's developer console to the provider configuration:\n 1. To register a Microsoft OAuth client, follow the instructions in [Quickstart: Register an app with the Azure Active Directory v2.0 endpoint](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-register-an-app). Note that this endpoint supports sign-in using Microsoft personal accounts as well as Azure Active Directory accounts. [Learn more](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-overview) about Azure Active Directory v2.0.\n 2. When registering apps with these providers, be sure to register the `*.firebaseapp.com` domain for your project as the redirect domain for your app.\n5. Click **Save**.\n\nAccess the `firebase::auth::Auth` class The `Auth` class is the gateway for all API calls.\n\n1. Add the Auth and App header files: \n\n ```c++\n #include \"firebase/app.h\"\n #include \"firebase/auth.h\"\n ```\n2. In your initialization code, create a [`firebase::App`](/docs/reference/cpp/class/firebase/app) class. \n\n ```c++\n #if defined(__ANDROID__)\n firebase::App* app =\n firebase::App::Create(firebase::AppOptions(), my_jni_env, my_activity);\n #else\n firebase::App* app = firebase::App::Create(firebase::AppOptions());\n #endif // defined(__ANDROID__)\n ```\n3. Acquire the `firebase::auth::Auth` class for your `firebase::App`. There is a one-to-one mapping between `App` and `Auth`. \n\n ```c++\n firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app);\n ```\n\nHandle the sign-in flow with the Firebase SDK\n\nTo handle the sign-in flow with the Firebase SDK, follow these steps:\n\n1. Construct an instance of a `FederatedOAuthProviderData` configured with\n the provider id appropriate for Microsoft.\n\n firebase::auth::FederatedOAuthProviderData\n provider_data(firebase::auth::MicrosoftAuthProvider::kProviderId);\n\n2. **Optional**: Specify additional custom OAuth parameters that you want to\n send with the OAuth request.\n\n // Prompt user to re-authenticate to Microsoft.\n provider_data.custom_parameters[\"prompt\"] = \"login\";\n\n // Target specific email with login hint.\n provider_data.custom_parameters[\"login_hint\"] =\n \"user@firstadd.onmicrosoft.com\";\n\n For the parameters Microsoft supports, see the\n [Microsoft OAuth documentation](https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code).\n Note that you can't pass Firebase-required parameters with\n `setCustomParameters()`. These parameters are **client_id** ,\n **response_type** , **redirect_uri** , **state** , **scope** and\n **response_mode**.\n\n To allow only users from a particular Azure AD tenant to sign\n into the application, either the friendly domain name of the Azure AD tenant\n or the tenant's GUID identifier can be used. This can be done by specifying\n the \"tenant\" field in the custom parameters object. \n\n // Optional \"tenant\" parameter in case you are using an Azure AD tenant.\n // eg. '8eaef023-2b34-4da1-9baa-8bc8c9d6a490' or 'contoso.onmicrosoft.com'\n // or \"common\" for tenant-independent tokens.\n // The default value is \"common\".\n provider_data.custom_parameters[\"tenant\"] =\"TENANT_ID\";\n\n3. **Optional**: Specify additional OAuth 2.0 scopes beyond basic profile that\n you want to request from the authentication provider.\n\n provider_data.scopes.push_back(\"mail.read\");\n provider_data.scopes.push_back(\"calendars.read\");\n\n To learn more, refer to the\n [Microsoft permissions and consent documentation](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent).\n4. Once your provider data has been configured, use it to create a\n `FederatedOAuthProvider`.\n\n // Construct a FederatedOAuthProvider for use in Auth methods.\n firebase::auth::FederatedOAuthProvider provider(provider_data);\n\n5. Authenticate with Firebase using the Auth provider object. Note that unlike\n other FirebaseAuth operations, this will take control of your UI by popping\n up a web view in which the user can enter their credentials.\n\n To start the sign in flow, call `SignInWithProvider`: \n\n firebase::Future\u003cfirebase::auth::AuthResult\u003e result =\n auth-\u003eSignInWithProvider(provider_data);\n\n Your application may then wait or [register a callback on the Future](#register_callback_on_future).\n\n Using the OAuth access token, you can call the\n [Microsoft Graph API](https://docs.microsoft.com/en-us/graph/overview?toc=./toc.json&view=graph-rest-1.0).\n\n Unlike other providers supported by Firebase Auth, Microsoft does not\n provide a photo URL and instead, the binary data for a profile photo has to\n be requested via\n [Microsoft Graph API](https://docs.microsoft.com/en-us/graph/api/profilephoto-get?view=graph-rest-1.0).\n6. While the above examples focus on sign-in flows, you also have the\n ability to link a Microsoft Azure Active Directory provider to an existing\n user using `LinkWithProvider`. For example, you can link multiple\n providers to the same user allowing them to sign in with either.\n\n firebase::Future\u003cfirebase::auth::AuthResult\u003e result = user.LinkWithProvider(provider_data);\n\n7. The same pattern can be used with `ReauthenticateWithProvider` which can be\n used to retrieve fresh credentials for sensitive operations that require\n recent login.\n\n firebase::Future\u003cfirebase::auth::AuthResult\u003e result =\n user.ReauthenticateWithProvider(provider_data);\n\n Your application may then wait or [register a callback on\n the Future](#register_callback_on_future).\n\nAdvanced: Handle the sign-in flow manually\n\nUnlike other OAuth providers supported by Firebase such as Google, Facebook,\nand Twitter, where sign-in can directly be achieved with OAuth access token\nbased credentials, Firebase Auth does not support the same capability for\nproviders such as Microsoft due to the inability of the Firebase\nAuth server to verify the audience of Microsoft OAuth access tokens.\nThis is a critical security requirement and could expose applications and\nwebsites to replay attacks where a Microsoft OAuth access token obtained for\none project (attacker) can be used to sign in to another project (victim).\nInstead, Firebase Auth offers the ability to handle the entire OAuth flow and\nthe authorization code exchange using the OAuth client ID and secret\nconfigured in the Firebase Console. As the authorization code can only be used\nin conjunction with a specific client ID/secret, an authorization code\nobtained for one project cannot be used with another.\n\nIf these providers are required to be used in unsupported environments, a\nthird party OAuth library and\n[Firebase custom authentication](../admin/create-custom-tokens)\nwould need to be used. The former is needed to authenticate with the provider\nand the latter to exchange the provider's credential for a custom token.\n\nNext steps\n\nAfter a user signs in for the first time, a new user account is created and\nlinked to the credentials---that is, the user name and password, phone\nnumber, or auth provider information---the user signed in with. This new\naccount is stored as part of your Firebase project, and can be used to identify\na user across every app in your project, regardless of how the user signs in.\n\n- In your apps, you can get the user's basic profile information from the\n [`firebase::auth::User`](/docs/reference/cpp/class/firebase/auth/user) object:\n\n ```c++\n firebase::auth::User user = auth-\u003ecurrent_user();\n if (user.is_valid()) {\n std::string name = user.display_name();\n std::string email = user.email();\n std::string photo_url = user.photo_url();\n // The user's ID, unique to the Firebase project.\n // Do NOT use this value to authenticate with your backend server,\n // if you have one. Use firebase::auth::User::Token() instead.\n std::string uid = user.uid();\n }\n ```\n- In your Firebase Realtime Database and Cloud Storage\n [Security Rules](/docs/database/security/user-security), you can\n get the signed-in user's unique user ID from the `auth` variable,\n and use it to control what data a user can access.\n\nYou can allow users to sign in to your app using multiple authentication\nproviders by [linking auth provider credentials to an\nexisting user account.](/docs/auth/cpp/account-linking)\n\nTo sign out a user, call [`SignOut()`](/docs/reference/cpp/class/firebase/auth/auth#signout): \n\n```c++\nauth-\u003eSignOut();\n```"]]