使用 Yahoo 和 Unity 进行身份验证
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
如需让您的用户能够通过 OAuth 提供方(如 Yahoo)进行 Firebase 身份验证,您可以使用 Firebase SDK 执行端到端登录流程,将基于 Web 的通用 OAuth 登录机制集成到您的应用中。由于此流程需要使用基于电话的 Firebase SDK,因此它仅支持 Android 和 Apple 平台。
准备工作
在使用 Firebase Authentication 之前,您需要:
请注意,为了将 Firebase 添加到 Unity 项目,需要在 Firebase 控制台中和打开的 Unity 项目中执行若干任务(例如,从控制台下载 Firebase 配置文件,然后将配置文件移到 Unity 项目中)。
访问 Firebase.Auth.FirebaseAuth
类
FirebaseAuth
类是所有 API 调用都需要通过的门户,此类可通过
FirebaseAuth.DefaultInstance 访问。
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
使用 Firebase SDK 处理登录流程
如需使用 Firebase SDK 处理登录流程,请按以下步骤操作:
构造一个配置了适合 Yahoo 的提供方 ID 的 FederatedOAuthProviderData
实例。
Firebase.Auth.FederatedOAuthProviderData providerData =
new Firebase.Auth.FederatedOAuthProviderData();
providerData.ProviderId = Firebase.Auth.YahooAuthProvider.ProviderId;
可选:指定您希望通过 OAuth 请求发送的其他自定义 OAuth 参数。
providerData.CustomParameters = new Dictionary<string,string>;
// Prompt user to re-authenticate to Yahoo.
providerData.CustomParameters.Add("prompt", "login");
// Localize to French.
providerData.CustomParameters.Add("language", "fr");
如需查看 Yahoo 支持的参数,请参阅 Yahoo OAuth 文档。
请注意,您不能使用 custom_parameters()
传递 Firebase 必需的参数。这些参数包括 client_id、redirect_uri、response_type、scope 和 state。
可选:指定您希望向身份验证提供方申请的 profile
和 email
之外的 OAuth 2.0 范围。如果您的应用需要通过 Yahoo API 访问用户私人数据,您需要在 Yahoo 开发者控制台的 API 权限下申请 Yahoo API 权限。申请的 OAuth 范围必须与应用的 API 权限中预配置的范围完全匹配。例如,如果您申请了对用户通讯录的读写权限,并已在应用的 API 权限中预配置相应权限,则必须传递 sdct-w
而不是只读 OAuth 范围 sdct-r
。否则将导致流程失败,并向最终用户显示错误消息。
providerData.Scopes = new List<string>();
// Request access to Yahoo Mail API.
providerData.Scopes.Add("mail-r");
// This must be preconfigured in the app's API permissions.
providerData.Scopes.Add("sdct-w");
如需了解详情,请参阅 Yahoo 范围文档。
提供方数据配置完成后,请使用它来创建 FederatedOAuthProvider。
// Construct a FederatedOAuthProvider for use in Auth methods.
Firebase.Auth.FederatedOAuthProvider provider =
new Firebase.Auth.FederatedOAuthProvider();
provider.SetProviderData(providerData);
使用 Auth 提供方对象进行 Firebase 身份验证。请注意,与其他 FirebaseAuth 操作不同,此操作会弹出可供用户输入其凭据的网页视图,从而控制您的界面。
如需启动登录流程,请调用 SignInAndRetrieveDataWithCredentialAsync
:
<<../_includes/_sign_in_with_provider_unity.md>>>
以上示例侧重的是登录流程。除此之外,您也可以使用 LinkWithProviderAsync
将 Yahoo 提供方与现有用户相关联。例如,您可以将多个提供方关联至同一个用户,以便使用任意一个进行登录。
user.LinkWithProviderAsync(provider).ContinueOnMainThread(task => {
if (task.IsCanceled) {
Debug.LogError("LinkWithProviderAsync was canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError("LinkWithProviderAsync encountered an error: "
+ task.Exception);
return;
}
Firebase.Auth.AuthResult authResult = task.Result;
Firebase.Auth.FirebaseUser user = authResult.User;
Debug.LogFormat("User linked successfully: {0} ({1})",
user.DisplayName, user.UserId);
});
上述模式同样适用于 ReauthenticateWithProviderAsync
,对于要求用户必须在近期内登录过才能执行的敏感操作,可使用它来检索新的凭据。
user.ReauthenticateWithProviderAsync(provider).ContinueOnMainThread(task => {
if (task.IsCanceled) {
Debug.LogError("ReauthenticateWithProviderAsync was canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError(
"ReauthenticateWithProviderAsync encountered an error: " +
task.Exception);
return;
}
Firebase.Auth.AuthResult authResult = task.Result;
Firebase.Auth.FirebaseUser user = authResult.User;
Debug.LogFormat("User reauthenticated successfully: {0} ({1})",
user.DisplayName, user.UserId);
});
高级:手动处理登录流程
Firebase 所支持的其他 OAuth 提供方(如 Google、Facebook 和 Twitter)可以通过基于 OAuth 访问令牌的凭据直接实现登录,Firebase Auth 则不同。由于 Firebase Auth 服务器无法验证 Yahoo 等提供方的 OAuth 访问令牌的目标设备,因此 Firebase Auth 不支持通过这些提供方直接登录。
这是一项关键的安全要求,不满足该要求的应用和网站可能会受到重放攻击的威胁。在这种情况下,为某个项目(攻击者)获取的 Yahoo 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-08。
[null,null,["最后更新时间 (UTC):2025-08-08。"],[],[],null,["You can let your users authenticate with Firebase using OAuth providers like\nYahoo by integrating web-based generic OAuth Login into your app using the\nFirebase SDK to carry out the end to end sign-in flow. Since this flow requires\nthe use of the phone-based Firebase SDKs, it is only supported on Android and\nApple platforms.\n\nBefore you begin\n\nBefore you can use\n[Firebase Authentication](/docs/reference/unity/namespace/firebase/auth),\nyou need to:\n\n- Register your Unity project and configure it to use Firebase.\n\n - If your Unity project already uses Firebase, then it's already\n registered and configured for Firebase.\n\n - If you don't have a Unity project, you can download a\n [sample app](//github.com/google/mechahamster).\n\n- Add the [Firebase Unity SDK](/download/unity) (specifically, `FirebaseAuth.unitypackage`) to\n your Unity project.\n\n| **Find detailed instructions for these initial\n| setup tasks in\n| [Add Firebase to your Unity project](/docs/unity/setup#prerequisites).**\n\nNote that adding Firebase to your Unity project involves tasks both in the\n[Firebase console](//console.firebase.google.com/) and in your open Unity project\n(for example, you download Firebase config files from the console, then move\nthem into your Unity project).\n\nAccess the `Firebase.Auth.FirebaseAuth` class The `FirebaseAuth` class is the gateway for all API calls. It is accessible through [FirebaseAuth.DefaultInstance](/docs/reference/unity/class/firebase/auth/firebase-auth#defaultinstance). \n\n```c#\nFirebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;\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 Yahoo.\n\n Firebase.Auth.FederatedOAuthProviderData providerData =\n new Firebase.Auth.FederatedOAuthProviderData();\n providerData.ProviderId = Firebase.Auth.YahooAuthProvider.ProviderId;\n\n2. **Optional**: Specify additional custom OAuth parameters that you want to\n send with the OAuth request.\n\n providerData.CustomParameters = new Dictionary\u003cstring,string\u003e;\n\n // Prompt user to re-authenticate to Yahoo.\n providerData.CustomParameters.Add(\"prompt\", \"login\");\n\n // Localize to French.\n providerData.CustomParameters.Add(\"language\", \"fr\");\n\n For the parameters Yahoo supports, see the\n [Yahoo OAuth documentation](https://developer.yahoo.com/oauth2/guide/openid_connect/getting_started.html).\n Note that you can't pass Firebase-required parameters with\n `custom_parameters()`. These parameters are **client_id** ,\n **redirect_uri** , **response_type** , **scope** and **state**.\n3. **Optional** : Specify additional OAuth 2.0 scopes beyond `profile` and\n `email` that you want to request from the authentication provider. If your\n application requires access to private user data from Yahoo APIs, you'll\n need to request permissions to Yahoo APIs under **API Permissions** in the\n Yahoo developer console. Requested OAuth scopes must be exact matches to the\n preconfigured ones in the app's API permissions. For example if, read/write\n access is requested to user contacts and preconfigured in the app's API\n permissions, `sdct-w` has to be passed instead of the readonly OAuth scope\n `sdct-r`. Otherwise,the flow will fail and an error would be shown to the\n end user.\n\n providerData.Scopes = new List\u003cstring\u003e();\n\n // Request access to Yahoo Mail API.\n providerData.Scopes.Add(\"mail-r\");\n // This must be preconfigured in the app's API permissions.\n providerData.Scopes.Add(\"sdct-w\");\n\n To learn more, refer to the\n [Yahoo scopes documentation](https://developer.yahoo.com/oauth2/guide/yahoo_scopes/).\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 =\n new Firebase.Auth.FederatedOAuthProvider();\n provider.SetProviderData(providerData);\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 `SignInAndRetrieveDataWithCredentialAsync`:\n\n\\\u003c\\\u003c../_includes/_sign_in_with_provider_unity.md\\\u003e\\\u003e\\\u003e\n\n1. While the above examples focus on sign-in flows, you also have the\n ability to link a Yahoo provider to an existing user using\n `LinkWithProviderAsync`. For example, you can link multiple\n providers to the same user allowing them to sign in with either.\n\n user.LinkWithProviderAsync(provider).ContinueOnMainThread(task =\u003e {\n if (task.IsCanceled) {\n Debug.LogError(\"LinkWithProviderAsync was canceled.\");\n return;\n }\n if (task.IsFaulted) {\n Debug.LogError(\"LinkWithProviderAsync encountered an error: \"\n + task.Exception);\n return;\n }\n\n Firebase.Auth.AuthResult authResult = task.Result;\n Firebase.Auth.FirebaseUser user = authResult.User;\n Debug.LogFormat(\"User linked successfully: {0} ({1})\",\n user.DisplayName, user.UserId);\n });\n\n2. The same pattern can be used with `ReauthenticateWithProviderAsync` which\n can be used to retrieve fresh credentials for sensitive operations that\n require recent login.\n\n user.ReauthenticateWithProviderAsync(provider).ContinueOnMainThread(task =\u003e {\n if (task.IsCanceled) {\n Debug.LogError(\"ReauthenticateWithProviderAsync was canceled.\");\n return;\n }\n if (task.IsFaulted) {\n Debug.LogError(\n \"ReauthenticateWithProviderAsync encountered an error: \" +\n task.Exception);\n return;\n }\n\n Firebase.Auth.AuthResult authResult = task.Result;\n Firebase.Auth.FirebaseUser user = authResult.User;\n Debug.LogFormat(\"User reauthenticated successfully: {0} ({1})\",\n user.DisplayName, user.UserId);\n });\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 Yahoo due to the inability of the Firebase\nAuth server to verify the audience of Yahoo OAuth access tokens.\nThis is a critical security requirement and could expose applications and\nwebsites to replay attacks where a Yahoo 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.FirebaseUser`](/docs/reference/unity/class/firebase/auth/firebase-user) object:\n\n ```c#\n Firebase.Auth.FirebaseUser user = auth.CurrentUser;\n if (user != null) {\n string name = user.DisplayName;\n string email = user.Email;\n System.Uri photo_url = user.PhotoUrl;\n // The user's Id, unique to the Firebase project.\n // Do NOT use this value to authenticate with your backend server, if you\n // have one; use User.TokenAsync() instead.\n string uid = user.UserId;\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/unity/account-linking)\n\nTo sign out a user, call [`SignOut()`](/docs/reference/unity/class/firebase/auth/firebase-auth#signout): \n\n```c#\nauth.SignOut();\n```"]]