Liên kết nhiều nhà cung cấp dịch vụ xác thực với một tài khoản trong Unity
Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Bạn có thể cho phép người dùng đăng nhập vào ứng dụng của mình bằng nhiều trình cung cấp dịch vụ xác thực bằng cách liên kết thông tin xác thực của trình cung cấp dịch vụ xác thực với một tài khoản người dùng hiện có.
Người dùng có thể nhận dạng bằng cùng một mã nhận dạng người dùng Firebase, bất kể nhà cung cấp dịch vụ xác thực mà họ dùng để đăng nhập. Ví dụ: người dùng đã đăng nhập bằng mật khẩu có thể liên kết một Tài khoản Google và đăng nhập bằng một trong hai phương thức này trong tương lai. Hoặc người dùng ẩn danh có thể liên kết tài khoản Facebook rồi sau đó đăng nhập bằng Facebook để tiếp tục sử dụng ứng dụng của bạn.
Trước khi bắt đầu
Thêm tính năng hỗ trợ cho 2 hoặc nhiều nhà cung cấp dịch vụ xác thực (có thể bao gồm cả xác thực ẩn danh) vào ứng dụng của bạn.
Lớp FirebaseAuth là cổng cho tất cả các lệnh gọi API.
Bạn có thể truy cập vào đối tượng này thông qua FirebaseAuth.DefaultInstance.
Liên kết thông tin đăng nhập của nhà cung cấp dịch vụ xác thực với tài khoản người dùng
Cách liên kết thông tin đăng nhập của nhà cung cấp dịch vụ xác thực với một tài khoản người dùng hiện có:
Đăng nhập cho người dùng bằng bất kỳ trình cung cấp hoặc phương thức xác thực nào.
Hoàn tất quy trình đăng nhập cho trình xác thực mới, nhưng không bao gồm việc gọi một trong các phương thức Firebase.Auth.FirebaseAuth.SignInAndRetrieveDataWithCredentialAsync. Ví dụ: lấy mã thông báo nhận dạng trên Google, mã thông báo truy cập Facebook hoặc email và mật khẩu của người dùng.
Lấy Firebase.Auth.Credential cho trình xác thực mới:
Truyền đối tượng Firebase.Auth.Credential đến phương thức LinkWithCredentialAsync của người dùng đã đăng nhập:
auth.CurrentUser.LinkWithCredentialAsync(credential).ContinueWith(task=>{if(task.IsCanceled){Debug.LogError("LinkWithCredentialAsync was canceled.");return;}if(task.IsFaulted){Debug.LogError("LinkWithCredentialAsync encountered an error: "+task.Exception);return;}Firebase.Auth.AuthResultresult=task.Result;Debug.LogFormat("Credentials successfully linked to Firebase user: {0} ({1})",result.User.DisplayName,result.User.UserId);});
Lệnh gọi đến LinkWithCredentialAsync sẽ không thành công nếu thông tin đăng nhập đã được liên kết với một tài khoản người dùng khác. Trong trường hợp này, bạn phải xử lý việc hợp nhất các tài khoản và dữ liệu liên kết cho phù hợp với ứng dụng của mình:
// Gather data for the currently signed in User.stringcurrentUserId=auth.CurrentUser.UserId;stringcurrentEmail=auth.CurrentUser.Email;stringcurrentDisplayName=auth.CurrentUser.DisplayName;System.UricurrentPhotoUrl=auth.CurrentUser.PhotoUrl;// Sign in with the new credentials.auth.SignInAndRetrieveDataWithCredentialAsync(credential).ContinueWith(task=>{if(task.IsCanceled){Debug.LogError("SignInAndRetrieveDataWithCredentialAsync was canceled.");return;}if(task.IsFaulted){Debug.LogError("SignInAndRetrieveDataWithCredentialAsync encountered an error: "+task.Exception);return;}Firebase.Auth.AuthResultresult=task.Result;Debug.LogFormat("User signed in successfully: {0} ({1})",result.User.DisplayName,result.User.UserId);// TODO: Merge app specific details using the newUser and values from the// previous user, saved above.});
Nếu lệnh gọi đến LinkWithCredentialAsync thành công, thì giờ đây, người dùng có thể đăng nhập bằng bất kỳ trình cung cấp dịch vụ xác thực được liên kết nào và truy cập vào cùng một dữ liệu Firebase.
Huỷ liên kết nhà cung cấp dịch vụ uỷ quyền khỏi tài khoản người dùng
Bạn có thể huỷ liên kết một nhà cung cấp dịch vụ uỷ quyền khỏi một tài khoản để người dùng không thể đăng nhập bằng nhà cung cấp đó nữa.
Để huỷ liên kết một nhà cung cấp dịch vụ uỷ quyền khỏi tài khoản người dùng, hãy truyền mã nhận dạng nhà cung cấp đến phương thức UnlinkAsync. Bạn có thể lấy mã nhận dạng nhà cung cấp của các nhà cung cấp dịch vụ uỷ quyền được liên kết với một người dùng bằng cách gọi ProviderData.
// Unlink the sign-in provider from the currently active user.// providerIdString is a string identifying a provider,// retrieved via FirebaseAuth.FetchProvidersForEmail().auth.CurrentUser.UnlinkAsync(providerIdString).ContinueWith(task=>{if(task.IsCanceled){Debug.LogError("UnlinkAsync was canceled.");return;}if(task.IsFaulted){Debug.LogError("UnlinkAsync encountered an error: "+task.Exception);return;}// The user has been unlinked from the provider.Firebase.Auth.AuthResultresult=task.Result;Debug.LogFormat("Credentials successfully unlinked from user: {0} ({1})",result.User.DisplayName,result.User.UserId);});
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 2025-09-03 UTC."],[],[],null,["| **Important** : There is a [known issue](https://github.com/firebase/firebase-js-sdk/issues/7675) that prevents `linkWithCredentials()` from working correctly in some projects. See the issue report for a workaround and the status of a fix.\n\nYou can allow users to sign in to your app using multiple authentication\nproviders by linking auth provider credentials to an existing user account.\nUsers are identifiable by the same Firebase user ID regardless of the\nauthentication provider they used to sign in. For example, a user who signed in\nwith a password can link a Google account and sign in with either method in the\nfuture. Or, an anonymous user can link a Facebook account and then, later, sign\nin with Facebook to continue using your app.\n\nBefore you begin\n\nAdd support for two or more authentication providers (possibly including\nanonymous authentication) to your app.\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\nLink auth provider credentials to a user account\n\nTo link auth provider credentials to an existing user account:\n\n1. Sign in the user using any authentication provider or method.\n2. Complete the sign-in flow for the new authentication provider up to, but not including, calling one of the [`Firebase.Auth.FirebaseAuth.SignInAndRetrieveDataWithCredentialAsync`](/docs/reference/unity/class/firebase/auth/firebase-auth#signinandretrievedatawithcredentialasync) methods. For example, get the user's Google ID token, Facebook access token, or email and password.\n3. Get a `Firebase.Auth.Credential` for the new authentication provider:\n\n **Google Sign-In** \n\n ```c#\n Firebase.Auth.Credential credential =\n Firebase.Auth.GoogleAuthProvider.GetCredential(googleIdToken, googleAccessToken);\n ```\n **Facebook Login** \n\n ```c#\n Firebase.Auth.Credential credential =\n Firebase.Auth.FacebookAuthProvider.GetCredential(accessToken);\n ```\n **Email-password sign-in** \n\n ```c#\n Firebase.Auth.Credential credential =\n Firebase.Auth.EmailAuthProvider.GetCredential(email, password);\n ```\n4. Pass the `Firebase.Auth.Credential` object to the signed-in user's\n `LinkWithCredentialAsync` method:\n\n ```c#\n auth.CurrentUser.LinkWithCredentialAsync(credential).ContinueWith(task =\u003e {\n if (task.IsCanceled) {\n Debug.LogError(\"LinkWithCredentialAsync was canceled.\");\n return;\n }\n if (task.IsFaulted) {\n Debug.LogError(\"LinkWithCredentialAsync encountered an error: \" + task.Exception);\n return;\n }\n\n Firebase.Auth.AuthResult result = task.Result;\n Debug.LogFormat(\"Credentials successfully linked to Firebase user: {0} ({1})\",\n result.User.DisplayName, result.User.UserId);\n });\n ```\n\n The call to `LinkWithCredentialAsync` will fail if the credentials are\n already linked to another user account. In this situation, you must handle\n merging the accounts and associated data as appropriate for your app: \n\n ```c#\n // Gather data for the currently signed in User.\n string currentUserId = auth.CurrentUser.UserId;\n string currentEmail = auth.CurrentUser.Email;\n string currentDisplayName = auth.CurrentUser.DisplayName;\n System.Uri currentPhotoUrl = auth.CurrentUser.PhotoUrl;\n\n // Sign in with the new credentials.\n auth.SignInAndRetrieveDataWithCredentialAsync(credential).ContinueWith(task =\u003e {\n if (task.IsCanceled) {\n Debug.LogError(\"SignInAndRetrieveDataWithCredentialAsync was canceled.\");\n return;\n }\n if (task.IsFaulted) {\n Debug.LogError(\"SignInAndRetrieveDataWithCredentialAsync encountered an error: \" + task.Exception);\n return;\n }\n\n Firebase.Auth.AuthResult result = task.Result;\n Debug.LogFormat(\"User signed in successfully: {0} ({1})\",\n result.User.DisplayName, result.User.UserId);\n\n // TODO: Merge app specific details using the newUser and values from the\n // previous user, saved above.\n });\n ```\n\nIf the call to `LinkWithCredentialAsync` succeeds, the user can now sign in using\nany linked authentication provider and access the same Firebase data.\n\nUnlink an auth provider from a user account\n\nYou can unlink an auth provider from an account, so that the user can no\nlonger sign in with that provider.\n\nTo unlink an auth provider from a user account, pass the provider ID to the\n`UnlinkAsync` method. You can get the provider IDs of the auth\nproviders linked to a user by calling\n[`ProviderData`](/docs/reference/unity/class/firebase/auth/firebase-user#providerdata). \n\n```c#\n// Unlink the sign-in provider from the currently active user.\n// providerIdString is a string identifying a provider,\n// retrieved via FirebaseAuth.FetchProvidersForEmail().\nauth.CurrentUser.UnlinkAsync(providerIdString).ContinueWith(task =\u003e {\n if (task.IsCanceled) {\n Debug.LogError(\"UnlinkAsync was canceled.\");\n return;\n }\n if (task.IsFaulted) {\n Debug.LogError(\"UnlinkAsync encountered an error: \" + task.Exception);\n return;\n }\n\n // The user has been unlinked from the provider.\n Firebase.Auth.AuthResult result = task.Result;\n Debug.LogFormat(\"Credentials successfully unlinked from user: {0} ({1})\",\n result.User.DisplayName, result.User.UserId);\n});\n```\n\nTroubleshooting\n\nIf you encounter errors when trying to link multiple accounts, see the\n[documentation on\nverified email addresses](https://firebase.google.com/docs/auth/users#verified_email_addresses)."]]