Collegare più provider di autenticazione a un account in Unity
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Puoi consentire agli utenti di accedere alla tua app utilizzando più autenticazioni
dei provider collegando le credenziali dei provider di autenticazione a un account utente esistente.
Gli utenti sono identificabili tramite lo stesso ID utente Firebase, indipendentemente dal
il provider di autenticazione utilizzato per accedere. Ad esempio, un utente che ha eseguito l'accesso
con una password puoi collegare un Account Google e accedere con uno dei due metodi nella
per il futuro. Oppure, un utente anonimo può collegare un account Facebook e poi firmare
con Facebook per continuare a usare la tua app.
Prima di iniziare
Aggiungi il supporto per due o più provider di autenticazione (che potrebbero includere
autenticazione anonima) alla tua app.
La classe FirebaseAuth è il gateway per tutte le chiamate API.
È accessibile tramite FirebaseAuth.DefaultInstance.
Collegare le credenziali del provider di autenticazione a un account utente
Per collegare le credenziali del provider di autenticazione a un account utente esistente:
Accedi all'utente utilizzando qualsiasi metodo o provider di autenticazione.
Completa il flusso di accesso per il nuovo provider di autenticazione fino alla chiamata di uno dei metodi Firebase.Auth.FirebaseAuth.SignInAndRetrieveDataWithCredentialAsync, esclusa questa operazione. Ad esempio, recupera
l'ID token di Google, il token di accesso di Facebook o l'email e la password dell'utente.
Richiedi un Firebase.Auth.Credential per il nuovo provider di autenticazione:
Trasmetti l'oggetto Firebase.Auth.Credential all'account dell'utente che ha eseguito l'accesso
Metodo LinkWithCredentialAsync:
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);});
La chiamata al numero LinkWithCredentialAsync non riuscirà se le credenziali sono
sono già collegati a un altro account utente. In questa situazione, devi gestire
unendo gli account e i dati associati in base alle esigenze della tua app:
// 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.});
Se la chiamata al numero LinkWithCredentialAsync ha esito positivo, l'utente può ora accedere utilizzando
a qualsiasi provider di autenticazione collegato e accedere agli stessi dati Firebase.
Scollegare un provider di autenticazione da un account utente
Puoi scollegare un provider di autenticazione da un account in modo che l'utente non possa più accedere con quel provider.
Per scollegare un provider di autenticazione da un account utente, passa l'ID provider al
UnlinkAsync. Puoi ottenere gli ID provider dell'autenticazione
i provider collegati a un utente chiamando
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);});
[null,null,["Ultimo aggiornamento 2025-08-08 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```"]]