使用 Microsoft 和 C++ 进行身份验证
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
如需让您的用户能够使用 OAuth 提供方(如 Microsoft Azure Active Directory)进行 Firebase 身份验证,您可以使用 Firebase SDK 执行端到端登录流程,将基于 Web 的通用 OAuth 登录机制集成到您的应用中。由于此流程需要使用基于电话的 Firebase SDK,因此它仅支持 Android 和 Apple 平台。
准备工作
- 将 Firebase 添加至您的 C++ 项目。
- 在 Firebase 控制台中,打开 Auth 部分。
- 在登录方法标签页中,启用 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 调用都需要通过的门户。
- 添加 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::App
对应的 firebase::auth::Auth
类。App
和 Auth
是一对一的映射关系。firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app);
使用 Firebase SDK 处理登录流程
如需使用 Firebase SDK 处理登录流程,请按以下步骤操作:
构建一个配置了适用于 Microsoft 的提供方 ID 的 FederatedOAuthProviderData
实例。
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()
传递 Firebase 必需的参数。这些参数包括 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);
使用 Auth 提供方对象进行 Firebase 身份验证。请注意,与其他 FirebaseAuth 操作不同,此操作会弹出可供用户输入其凭据的网页视图,从而控制您的界面。
如需启动登录流程,请调用 SignInWithProvider
:
firebase::Future<firebase::auth::AuthResult> result =
auth->SignInWithProvider(provider_data);
然后,您的应用可能会等待或注册一个针对 Future 的回调。
使用 OAuth 访问令牌,您可以调用 Microsoft Graph API。
与 Firebase Authentication 支持的其他提供方不同,Microsoft 不提供照片网址,您必须通过 Microsoft Graph API 来请求个人资料照片的二进制数据。
以上示例侧重的是登录流程。除此之外,您也可以使用 LinkWithProvider
将 Microsoft Azure Active Directory 提供方与现有用户相关联。例如,您可以将多个提供方与同一个用户关联,以便用户使用任一提供方服务进行登录。
firebase::Future<firebase::auth::AuthResult> result = user.LinkWithProvider(provider_data);
上述模式同样适用于 ReauthenticateWithProvider
,它可用来为要求用户必须有近期登录才能执行的敏感操作检索新的凭据。
firebase::Future<firebase::auth::AuthResult> result =
user.ReauthenticateWithProvider(provider_data);
然后,您的应用可能会等待或注册一个针对 Future 的回调。
高级:手动处理登录流程
Firebase 支持的其他 OAuth 提供方(如 Google、Facebook 和 Twitter)可以通过基于 OAuth 访问令牌的凭据直接实现登录,Firebase Auth 则不同。由于 Firebase Auth 服务器无法验证 Microsoft 等提供方的 OAuth 访问令牌的目标设备,因此 Firebase Auth 不支持通过这些提供方直接登录。
这是一项关键的安全要求,不满足该要求的应用和网站可能会受到重放攻击的威胁。在这种情况下,为某个项目(攻击者)获取的 Microsoft OAuth 访问令牌可能被用来登录另一个项目(受害者)。
因此,Firebase Auth 改为提供另一种功能,即使用在 Firebase 控制台中配置的 OAuth 客户端 ID 和密钥来处理整个 OAuth 流程和授权代码交换。由于授权代码只能与特定客户端 ID/密钥结合使用,因此为某个项目获取的授权代码不能用于另一个项目。
如果需要在不受支持的环境中使用这些提供方,则需使用第三方 OAuth 库和 Firebase 自定义身份验证。前者在通过提供方进行身份验证时需要用到,后者则用于将提供方的凭据交换成自定义令牌。
后续步骤
在用户首次登录后,系统会创建一个新的用户账号,并将其与该用户登录时使用的凭据(即用户名和密码、电话号码或者身份验证提供方信息)相关联。此新账号存储在您的 Firebase 项目中,无论用户采用何种方式登录,您项目中的每个应用都可以使用此账号来识别用户。
您可以通过将身份验证提供方凭据关联至现有用户账号,让用户可以使用多个身份验证提供方登录您的应用。
如需将用户退出登录,请调用 SignOut()
:
auth->SignOut();
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-16。
[null,null,["最后更新时间 (UTC):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```"]]