使用 Microsoft 和 C++ 進行驗證
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
您可以讓使用者使用 OAuth 供應商通過 Firebase 驗證,例如
整合網頁式一般 OAuth 登入機制的 Microsoft Azure Active Directory
進入您的應用程式,並透過 Firebase SDK 執行端對端登入流程。
這個流程需要使用手機式 Firebase SDK,因此
Android 和 Apple 平台。
事前準備
- 將 Firebase 新增至您的 C++ 專案。
- 在 Firebase 控制台中開啟「Auth」專區。
- 在「Sign in method」分頁中,啟用「Microsoft」供應商。
- 將供應商開發人員主控台中的「用戶端 ID」和「用戶端密鑰」新增至
提供者設定:
- 如要註冊 Microsoft OAuth 用戶端,請按照
快速入門導覽課程:使用 Azure Active Directory v2.0 端點註冊應用程式。
請注意,這個端點支援使用 Microsoft 個人帳戶和 Azure 登入
Active Directory 帳戶。
瞭解詳情
Azure Active Directory v2.0 的相關資訊。
- 向這些供應商註冊應用程式時,請務必註冊
專案的
*.firebaseapp.com
網域,做為專案的重新導向網域
應用程式。
- 按一下 [儲存]。
存取 firebase::auth::Auth
類別
Auth
類別是所有 API 呼叫的閘道,
- 新增驗證與應用程式標頭檔案:
#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::App
的 firebase::auth::Auth
類別。
App
和 Auth
之間有一對一的對應關係。
firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app);
使用 Firebase SDK 處理登入流程
如要使用 Firebase SDK 處理登入流程,請按照下列步驟操作:
建構已設定的 FederatedOAuthProviderData
例項
與 Microsoft 相關的提供者 ID
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 說明文件。
請注意,您無法透過
setCustomParameters()
。這些參數都是 client_id
response_type、redirect_uri、state、scope 和
response_mode:
只允許特定 Azure AD 用戶群的使用者簽署
插入應用程式,即 Azure AD 用戶群的易記網域名稱
可以使用用戶群 GUID ID。方法是指定
「用戶群」欄位的值。
// 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);
接著,您的應用程式會等待,或
在 Future 上註冊回呼。
使用 OAuth 存取權杖可讓您呼叫
Microsoft Graph API。
有別於 Firebase Auth 支援的其他供應商,Microsoft 不需要
提供相片網址,並改為個人資料相片的二進位資料
透過以下方式要求:
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);
接著,您的應用程式會等待或在
未來
進階:手動處理登入流程
不同於 Firebase 支援的其他 OAuth 供應商,例如 Google、Facebook
和 Twitter,使用 OAuth 存取權杖直接登入
基於這個原因,Firebase Auth 不支援
這是因為 Firebase 無法使用
驗證伺服器,用於驗證 Microsoft OAuth 存取權杖的目標對象。
這是重大的安全需求,可能會公開應用程式和
會導致網站重新發動攻擊,攻擊者必須取得 Microsoft OAuth 存取權杖
一個專案 (攻擊者) 可用來登入另一個專案 (受害者)。
而是讓 Firebase 驗證能夠處理整個 OAuth 流程,
使用 OAuth 用戶端 ID 和密鑰進行授權碼交換
就可在 Firebase 控制台設定因為授權碼
搭配特定的用戶端 ID/密鑰 (授權碼)
每項專案取得的 均無法與另一項專案搭配使用
如果必須在不支援的環境中使用這些提供者,
第三方 OAuth 程式庫
Firebase 自訂驗證
。需要前者才能向供應商進行驗證
和後者,用於交換自訂權杖的提供者憑證。
後續步驟
使用者首次登入後,系統會建立新的使用者帳戶
也就是使用者的名稱和密碼
號碼或驗證提供者資訊,也就是使用者登入時使用的網址。這項新功能
帳戶儲存為 Firebase 專案的一部分,可用來識別
即可限制使用者登入專案中的所有應用程式
您可以讓使用者透過多重驗證機制登入您的應用程式
將驗證供應商憑證連結至
現有的使用者帳戶
如要登出使用者,請呼叫
SignOut()
:
auth->SignOut();
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-16 (世界標準時間)。
[null,null,["上次更新時間:2025-08-16 (世界標準時間)。"],[],[],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```"]]