Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Accesso degli utenti con Facebook
Questo documento mostra come utilizzare Identity Platform per consentire agli utenti di accedere con Facebook.
Prima di iniziare
Questo tutorial presuppone che tu abbia già attivato Identity Platform e che tu abbia un'app web di base scritta utilizzando HTML e JavaScript. Per scoprire come, consulta la guida rapida.
Configurare Facebook come provider
Per configurare Facebook come provider di identità:
Vai alla pagina Provider di identità nella Google Cloud console.
Inserisci l'ID app e l'App Secret di Facebook. Se
non hai ancora un ID e un segreto, puoi ottenerne uno dalla pagina
Facebook for Developers.
Configura l'URI elencato in Configura Facebook come URI di reindirizzamento OAuth valido per la tua app Facebook. Se hai configurato un dominio personalizzato in Identity Platform, aggiornate l'URI di reindirizzamento nella configurazione dell'app Facebook in modo da utilizzare il dominio personalizzato anziché il dominio predefinito. Ad esempio, cambia https://myproject.firebaseapp.com/__/auth/handler in
https://auth.myownpersonaldomain.com/__/auth/handler.
Registra i domini della tua app facendo clic su Aggiungi dominio in Domini autorizzati. Per scopi di sviluppo, localhost è già attivato per impostazione predefinita.
In Configura l'applicazione, fai clic su Dettagli di configurazione. Copia lo snippet nel codice dell'app per inizializzare l'SDK client di Identity Platform.
(Facoltativo) Aggiungi gli ambiti OAuth. Gli ambiti specificano quali dati stai richiedendo a Facebook. I dati più sensibili potrebbero richiedere scopi specifici. Consulta la documentazione del fornitore per determinare gli ambiti di cui ha bisogno la tua app.
JavaScript
provider.addScope('user_birthday');
(Facoltativo) Localizza il flusso di autenticazione. Puoi specificare una lingua o utilizzare la lingua predefinita del dispositivo:
JavaScript
firebase.auth().languageCode='it';// To apply the default browser preference instead of explicitly setting it.// firebase.auth().useDeviceLanguage();
(Facoltativo) Specifica altri parametri OAuth personalizzati. Si tratta di parametri specifici di Facebook e vengono in genere utilizzati per personalizzare l'esperienza di autenticazione. Non puoi passare parametri riservati da OAuth o Identity Platform.
Utilizza l'oggetto del provider Facebook per far accedere l'utente. Puoi aprire una finestra popup o reindirizzare la pagina corrente. Il reindirizzamento è più semplice per gli utenti che utilizzano dispositivi mobili.
Per visualizzare un popup, chiama signInWithPopup():
JavaScript
firebase.auth().signInWithPopup(provider).then((result)=>{/** @type {firebase.auth.OAuthCredential} */varcredential=result.credential;// The signed-in user info.varuser=result.user;// This gives you a Facebook Access Token. You can use it to access the Facebook API.varaccessToken=credential.accessToken;// ...}).catch((error)=>{// Handle Errors here.varerrorCode=error.code;varerrorMessage=error.message;// The email of the user's account used.varemail=error.email;// The firebase.auth.AuthCredential type that was used.varcredential=error.credential;// ...});
Per reindirizzare la pagina, chiama prima signInWithRedirect().
Segui le best practice quando utilizzi signInWithRedirect, linkWithRedirect o reauthenticateWithRedirect.
JavaScript
firebase.auth().signInWithRedirect(provider);
Poi, recupera il token di Facebook chiamando getRedirectResult()
al caricamento della pagina:
JavaScript
firebase.auth().getRedirectResult().then((result)=>{if(result.credential){/** @type {firebase.auth.OAuthCredential} */varcredential=result.credential;// This gives you a Facebook Access Token. You can use it to access the Facebook API.vartoken=credential.accessToken;// ...}// The signed-in user info.varuser=result.user;}).catch((error)=>{// Handle Errors here.varerrorCode=error.code;varerrorMessage=error.message;// The email of the user's account used.varemail=error.email;// The firebase.auth.AuthCredential type that was used.varcredential=error.credential;// ...});
Una volta ottenuto un token di accesso, puoi utilizzarlo per chiamare l'API Facebook.
Ad esempio:
Se non vuoi utilizzare l'SDK client, puoi gestire manualmente anche il flusso di accesso.
Questo metodo di accesso supporta anche l'accesso con Facebook per i giochi come fornitore di identità. Identity Platform non supporta l'implementazione manuale di Accesso con Facebook per i giochi. Accetta solo i token per lo scambio delle credenziali di Identity Platform.
Per integrare l'autenticazione di Facebook o Facebook Login per i giochi nella tua app, segui i passaggi descritti nella documentazione per gli sviluppatori:
Utilizza le credenziali per far accedere l'utente con Identity Platform:
JavaScript
// Sign in with the credential from the user.firebase.auth().signInWithCredential(credential).then((result)=>{// Signed in// ...}).catch((error)=>{// Handle Errors here.consterrorCode=error.code;consterrorMessage=error.message;// The email of the user's account used.constemail=error.email;// ...});
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-09 UTC."],[[["\u003cp\u003eThis guide outlines the process of enabling Facebook as an identity provider within Identity Platform, including acquiring the necessary App ID and App Secret from Facebook.\u003c/p\u003e\n"],["\u003cp\u003eThe document details how to configure Facebook as a provider by setting the valid OAuth redirect URI in your Facebook app and registering your app's domains under Authorized Domains.\u003c/p\u003e\n"],["\u003cp\u003eThe process for signing in users with the client SDK using the Facebook provider object is demonstrated, offering options for both pop-up windows and page redirection, with code examples provided.\u003c/p\u003e\n"],["\u003cp\u003eFor manual sign-in, the guide explains how to integrate Facebook or Facebook Login for Gaming authentication, then exchange the received token for an Identity Platform credential to sign in users.\u003c/p\u003e\n"],["\u003cp\u003eIt is also important to know that HTTPS is required for production apps by Facebook, and using \u003ccode\u003ehttp://localhost\u003c/code\u003e for local development requires your Facebook app to be in development mode.\u003c/p\u003e\n"]]],[],null,["Signing in users with Facebook\n\nThis document shows you how to use Identity Platform to sign in users with\nFacebook.\n\nBefore you begin\n\nThis tutorial assumes you've already enabled Identity Platform, and have a\nbasic web app written using HTML and JavaScript. See the\n[Quickstart](/identity-platform/docs/sign-in-user-email) to learn how.\n\nConfiguring Facebook as a provider\n\nTo configure Facebook as an identity provider:\n\n1. Go to the **Identity Providers** page in the Google Cloud console.\n\n [Go to the Identity Providers page](https://console.cloud.google.com/customer-identity/providers)\n2. Click **Add A Provider**.\n\n3. Select **Facebook** from the list.\n\n4. Enter your Facebook **App ID** and **App Secret** . If\n you don't already have an ID and secret, you can obtain one from the\n [Facebook for Developers](https://developers.facebook.com/apps) page.\n\n5. Configure the URI listed under **Configure Facebook** as a valid OAuth\n redirect URI for your Facebook app. If you configured a custom domain in Identity Platform,\n update the redirect URI in your Facebook app configuration to use the custom domain instead\n of the default domain. For example, change `https://myproject.firebaseapp.com/__/auth/handler` to\n `https://auth.myownpersonaldomain.com/__/auth/handler`.\n\n6. Register your app's domains by clicking **Add Domain** under\n **Authorized Domains** . For development purposes, `localhost` is already\n enabled by default.\n\n | **Important:** In projects created after April 28, 2025, Identity Platform no longer includes `localhost` as an authorized domain by default. Google strongly discourages the use of `localhost` in production projects. If you choose to authorize `localhost`, you can manually add it in the **Settings** page, in **Authorized Domains** , by clicking **Add Domain**.\n7. Under **Configure your application** , click **Setup Details**. Copy the\n snippet into your app's code to initialize the Identity Platform\n client SDK.\n\n8. Click **Save**.\n\nSigning in users with the client SDK\n\n1. Create an instance of the Facebook provider object:\n\n JavaScript \n\n var provider = new firebase.auth.FacebookAuthProvider();\n\n2. **Optional:** Add OAuth scopes. Scopes specify what data you are\n requesting from Facebook. More sensitive data may require specific\n scopes. Consult the provider's\n [documentation](https://developers.facebook.com/docs/facebook-login/permissions)\n to determine what scopes your app needs.\n\n JavaScript \n\n provider.addScope('user_birthday');\n\n3. **Optional:** Localize the authentication flow. You can specify a language,\n or use the device's default language:\n\n JavaScript \n\n firebase.auth().languageCode = 'it';\n // To apply the default browser preference instead of explicitly setting it.\n // firebase.auth().useDeviceLanguage();\n\n4. **Optional:** Specify additional custom OAuth parameters. These are\n specific to Facebook, and are typically used to customize the\n authentication experience. You can't pass parameters reserved by OAuth or Identity Platform.\n\n JavaScript \n\n provider.setCustomParameters({\n 'display': 'popup'\n });\n\n5. Use the Facebook provider object to sign in the user. You can either\n open a pop-up window, or redirect the current page. Redirecting is easier\n for users on mobile devices.\n\n\n | **Note:** Facebook requires HTTPS for production apps, and does not allow login with insecure hosts. If you're developing locally using the `http://localhost` origin, ensure your Facebook app is in development mode, and that you're signing in with a registered test account.\n\n \u003cbr /\u003e\n\n To show a pop-up, call `signInWithPopup()`: \n\n JavaScript \n\n firebase\n .auth()\n .signInWithPopup(provider)\n .then((result) =\u003e {\n /** @type {firebase.auth.OAuthCredential} */\n var credential = result.credential;\n\n // The signed-in user info.\n var user = result.user;\n\n // This gives you a Facebook Access Token. You can use it to access the Facebook API.\n var accessToken = credential.accessToken;\n\n // ...\n })\n .catch((error) =\u003e {\n // Handle Errors here.\n var errorCode = error.code;\n var errorMessage = error.message;\n // The email of the user's account used.\n var email = error.email;\n // The firebase.auth.AuthCredential type that was used.\n var credential = error.credential;\n\n // ...\n });\n\n To redirect the page, first call `signInWithRedirect()`.\n\n\n Follow the [best practices](/identity-platform/docs/web/redirect-best-practices) when using `signInWithRedirect`, `linkWithRedirect`, or `reauthenticateWithRedirect`.\n\n\n JavaScript \n\n firebase.auth().signInWithRedirect(provider);\n\n Then, retrieve the Facebook token by calling `getRedirectResult()`\n when your page loads: \n\n JavaScript \n\n firebase.auth()\n .getRedirectResult()\n .then((result) =\u003e {\n if (result.credential) {\n /** @type {firebase.auth.OAuthCredential} */\n var credential = result.credential;\n\n // This gives you a Facebook Access Token. You can use it to access the Facebook API.\n var token = credential.accessToken;\n // ...\n }\n // The signed-in user info.\n var user = result.user;\n }).catch((error) =\u003e {\n // Handle Errors here.\n var errorCode = error.code;\n var errorMessage = error.message;\n // The email of the user's account used.\n var email = error.email;\n // The firebase.auth.AuthCredential type that was used.\n var credential = error.credential;\n // ...\n });\n\nOnce you have an access token, you can use it to call the Facebook API.\nFor example: \n\nREST \n\n```bash\ncurl \"https://graph.facebook.com/me?fields=id,name&access_token=[TOKEN]\"\n```\n\nSigning in users manually\n\nIf you don't want to use the client SDK, you can also handle the sign-in\nflow manually.\n\nThis sign-in method also supports Facebook Login for Gaming as\nan IdP. Identity Platform doesn't support [manually implementing Facebook Login for Gaming](https://developers.facebook.com/docs/games/social-and-retention/features/login-for-gaming#manually-implement-facebook-login-for-gaming). It only accepts the tokens for exchanging Identity Platform credentials.\n\n1. Integrate Facebook or Facebook Login for Gaming authentication into your\n app by following the steps in their developer documentation:\n\n - [Facebook developer documentation](https://developers.facebook.com/docs/facebook-login/web)\n - [Facebook Login for Gaming developer documentation](https://developers.facebook.com/docs/games/social-and-retention/features/login-for-gaming#using-facebook-sdk)\n2. Sign in the user with Facebook or Facebook Login for Gaming using the\n flow you implemented in the previous step.\n\n3. Exchange the token you receive from Facebook or Facebook Login for\n Gaming for an Identity Platform credential:\n\n JavaScript \n\n var credential = firebase.auth.FacebookAuthProvider.credential(accessToken);\n\n4. Use the credential to sign in the user with Identity Platform:\n\n JavaScript \n\n // Sign in with the credential from the user.\n firebase.auth()\n .signInWithCredential(credential)\n .then((result) =\u003e {\n // Signed in\n // ...\n })\n .catch((error) =\u003e {\n // Handle Errors here.\n const errorCode = error.code;\n const errorMessage = error.message;\n // The email of the user's account used.\n const email = error.email;\n // ...\n });\n\nWhat's next\n\n- Learn more about [Identity Platform users](/identity-platform/docs/concepts-manage-users).\n- Sign in users with [other identity providers](/identity-platform/docs/how-to#signing-in-users)."]]