使用 Yahoo 和 Unity 驗證
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
您可以讓使用者使用 OAuth 供應商通過 Firebase 驗證,例如
Yahoo,使用
可使用 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 處理登入流程,請按照下列步驟操作:
建構已設定的 FederatedOAuthProviderData
例項
適用於 Yahoo 的提供者 ID。
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()
。這些參數都是 client_id
redirect_uri、response_type、scope 和 state。
選用:指定 profile
和 以外其他 OAuth 2.0 範圍
您想要向驗證供應商要求的 email
。如果您的
應用程式必須從 Yahoo API 存取使用者私人資料,而您
必須向 Yahoo API 提出「API 權限」要求
Yahoo! 開發人員控制台。要求的 OAuth 範圍必須與
。舉例來說,如果讀取/寫入
應用程式將要求存取使用者聯絡人,並在應用程式的 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);
使用驗證提供者物件向 Firebase 進行驗證。請注意,這不像
其他 FirebaseAuth 作業,這會透過彈出通訊視窗控制您的 UI
供使用者輸入憑證的網頁檢視畫面。
如要啟動登入流程,請呼叫 SignInAndRetrieveDataWithCredentialAsync
:
<<../_Include/_sign_in_with_provider_unity.md>>>
以上範例著重登入流程,不過您可以
使用
LinkWithProviderAsync
。舉例來說
以便將兩者登入
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 無法使用
驗證伺服器,用於驗證 Yahoo OAuth 存取權杖的目標對象。
這是重大的安全需求,可能會公開應用程式和
網站重新發動攻擊,亦即為
一個專案 (攻擊者) 可用來登入另一個專案 (受害者)。
而是讓 Firebase 驗證能夠處理整個 OAuth 流程,
使用 OAuth 用戶端 ID 和密鑰進行授權碼交換
就可在 Firebase 控制台設定因為授權碼
搭配特定的用戶端 ID/密鑰 (授權碼)
每項專案取得的 均無法與另一項專案搭配使用
如果必須在不支援的環境中使用這些提供者,
第三方 OAuth 程式庫
Firebase 自訂驗證
。需要前者才能向供應商進行驗證
和後者,用於交換自訂權杖的提供者憑證。
後續步驟
使用者首次登入後,系統會建立新的使用者帳戶
也就是使用者的名稱和密碼
號碼或驗證提供者資訊,也就是使用者登入時使用的網址。這項新功能
帳戶儲存為 Firebase 專案的一部分,可用來識別
即可限制使用者登入專案中的所有應用程式
您可以讓使用者透過多重驗證機制登入您的應用程式
將驗證供應商憑證連結至
現有的使用者帳戶
如要登出使用者,請呼叫
SignOut()
:
auth.SignOut();
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-08 (世界標準時間)。
[null,null,["上次更新時間:2025-08-08 (世界標準時間)。"],[],[],null,["# Authenticate Using Yahoo and Unity\n\nYou 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----------------\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\n---------------------------------------------\n\nThe `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---------------------------------------------\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------------------------------------------\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----------\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```"]]