Puoi consentire agli utenti di autenticarsi con Firebase utilizzando i propri account Twitter integrando l'autenticazione Twitter nella tua app. Puoi integrare l'autenticazione Twitter utilizzando l'SDK Firebase per eseguire il flusso di accesso oppure eseguendo manualmente il flusso OAuth di Twitter e passando il token di accesso e il secret risultanti a Firebase.
Prima di iniziare
- Aggiungi Firebase al tuo progetto JavaScript.
- Nella console Firebase, vai a Sicurezza > Autenticazione.
- Nella scheda Metodo di accesso, attiva il provider di accesso Twitter.
-
Aggiungi la chiave API e il secret API dalla console per sviluppatori del provider
alla configurazione del provider:
- Registra la tua app come applicazione per sviluppatori su Twitter e ottieni la chiave API e il secret API OAuth della tua app.
-
Assicurati che l'URI di reindirizzamento OAuth di Firebase (ad esempio,
my-app-12345.firebaseapp.com/__/auth/handler) sia impostato come URL di callback di autorizzazione nella pagina delle impostazioni dell'app nella configurazione dell'app Twitter.
- Fai clic su Salva.
Gestire il flusso di accesso con l'SDK Firebase
Se stai creando un'app web, il modo più semplice per autenticare gli utenti con Firebase utilizzando i loro account Twitter è gestire il flusso di accesso con l'SDK Firebase JavaScript. Se vuoi autenticare un utente in Node.js o in un altro ambiente non browser, devi gestire manualmente il flusso di accesso.
Per gestire il flusso di accesso con l'SDK Firebase JavaScript, segui questi passaggi:
- Crea un'istanza dell'oggetto provider Twitter:
Web
import { TwitterAuthProvider } from "firebase/auth"; const provider = new TwitterAuthProvider();
Web
var provider = new firebase.auth.TwitterAuthProvider();
- (Facoltativo): per localizzare il flusso OAuth del provider nella lingua preferita dell'utente senza passare esplicitamente i parametri OAuth personalizzati pertinenti, aggiorna il codice della lingua nell'istanza Auth prima di avviare il flusso OAuth. Ad esempio:
Web
import { getAuth } from "firebase/auth"; const auth = getAuth(); auth.languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // auth.useDeviceLanguage();
Web
firebase.auth().languageCode = 'it'; // To apply the default browser preference instead of explicitly setting it. // firebase.auth().useDeviceLanguage();
- (Facoltativo): specifica parametri aggiuntivi del fornitore OAuth personalizzato
da inviare con la richiesta OAuth. Per aggiungere un parametro personalizzato, chiama
setCustomParameterssul provider inizializzato con un oggetto contenente la chiave come specificato nella documentazione del provider OAuth e il valore corrispondente. Ad esempio:I parametri OAuth obbligatori riservati non sono consentiti e verranno ignorati. Per saperne di più, consulta il riferimento del fornitore di autenticazione.Web
provider.setCustomParameters({ 'lang': 'es' });
Web
provider.setCustomParameters({ 'lang': 'es' });
- Esegui l'autenticazione con Firebase utilizzando l'oggetto provider Twitter. Puoi
chiedere agli utenti di accedere con i propri account Twitter aprendo una
finestra popup o reindirizzando alla pagina di accesso. Il metodo di reindirizzamento è
preferito sui dispositivi mobili.
- Per accedere con una finestra popup, chiama
signInWithPopup:Tieni presente inoltre che puoi recuperare il token OAuth del provider Twitter, che può essere utilizzato per recuperare dati aggiuntivi utilizzando le API Twitter.Web
import { getAuth, signInWithPopup, TwitterAuthProvider } from "firebase/auth"; const auth = getAuth(); signInWithPopup(auth, provider) .then((result) => { // This gives you a the Twitter OAuth 1.0 Access Token and Secret. // You can use these server side with your app's credentials to access the Twitter API. const credential = TwitterAuthProvider.credentialFromResult(result); const token = credential.accessToken; const secret = credential.secret; // The signed-in user info. const user = result.user; // IdP data available using getAdditionalUserInfo(result) // ... }).catch((error) => { // Handle Errors here. const errorCode = error.code; const errorMessage = error.message; // The email of the user's account used. const email = error.customData.email; // The AuthCredential type that was used. const credential = TwitterAuthProvider.credentialFromError(error); // ... });
Web
firebase .auth() .signInWithPopup(provider) .then((result) => { /** @type {firebase.auth.OAuthCredential} */ var credential = result.credential; // This gives you a the Twitter OAuth 1.0 Access Token and Secret. // You can use these server side with your app's credentials to access the Twitter API. var token = credential.accessToken; var secret = credential.secret; // The signed-in user info. var user = result.user; // IdP data available in result.additionalUserInfo.profile. // ... }).catch((error) => { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; // ... });
È anche qui che puoi rilevare e gestire gli errori. Per un elenco dei codici di errore, consulta la documentazione di riferimento sull'autenticazione.
- Per accedere reindirizzando alla pagina di accesso, chiama
signInWithRedirect: Segui le best practice quando utilizzi `signInWithRedirect`.Poi, puoi anche recuperare il token OAuth del provider Twitter chiamandoWeb
import { getAuth, signInWithRedirect } from "firebase/auth"; const auth = getAuth(); signInWithRedirect(auth, provider);
Web
firebase.auth().signInWithRedirect(provider);
getRedirectResultquando la pagina viene caricata:È anche qui che puoi rilevare e gestire gli errori. Per un elenco dei codici di errore, consulta la documentazione di riferimento sull'autenticazione.Web
import { getAuth, getRedirectResult, TwitterAuthProvider } from "firebase/auth"; const auth = getAuth(); getRedirectResult(auth) .then((result) => { // This gives you a the Twitter OAuth 1.0 Access Token and Secret. // You can use these server side with your app's credentials to access the Twitter API. const credential = TwitterAuthProvider.credentialFromResult(result); const token = credential.accessToken; const secret = credential.secret; // ... // The signed-in user info. const user = result.user; // IdP data available using getAdditionalUserInfo(result) // ... }).catch((error) => { // Handle Errors here. const errorCode = error.code; const errorMessage = error.message; // The email of the user's account used. const email = error.customData.email; // The AuthCredential type that was used. const credential = TwitterAuthProvider.credentialFromError(error); // ... });
Web
firebase.auth() .getRedirectResult() .then((result) => { if (result.credential) { /** @type {firebase.auth.OAuthCredential} */ var credential = result.credential; // This gives you a the Twitter OAuth 1.0 Access Token and Secret. // You can use these server side with your app's credentials to access the Twitter API. var token = credential.accessToken; var secret = credential.secret; // ... } // The signed-in user info. var user = result.user; // IdP data available in result.additionalUserInfo.profile. // ... }).catch((error) => { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; // ... });
- Per accedere con una finestra popup, chiama
Gestire manualmente il flusso di accesso
Puoi anche eseguire l'autenticazione con Firebase utilizzando un account Twitter gestendo il flusso di accesso chiamando gli endpoint OAuth di Twitter:
- Integra l'autenticazione Twitter nella tua app seguendo la documentazione per sviluppatori. Al termine del flusso di accesso a Twitter, riceverai un token di accesso OAuth e un segreto OAuth.
- Se devi accedere a un'applicazione Node.js, invia il token di accesso OAuth e il segreto OAuth all'applicazione Node.js.
- Dopo che un utente ha eseguito l'accesso con Twitter, scambia il token di accesso OAuth e il secret OAuth con una credenziale Firebase:
var credential = firebase.auth.TwitterAuthProvider.credential(token, secret);
- Esegui l'autenticazione con Firebase utilizzando le credenziali Firebase:
Web
import { getAuth, signInWithCredential, FacebookAuthProvider } from "firebase/auth"; // Sign in with the credential from the Facebook user. const auth = getAuth(); signInWithCredential(auth, credential) .then((result) => { // Signed in const credential = FacebookAuthProvider.credentialFromResult(result); }) .catch((error) => { // Handle Errors here. const errorCode = error.code; const errorMessage = error.message; // The email of the user's account used. const email = error.customData.email; // The AuthCredential type that was used. const credential = FacebookAuthProvider.credentialFromError(error); // ... });
Web
// Sign in with the credential from the Facebook user. firebase.auth().signInWithCredential(credential) .then((result) => { // Signed in var credential = result.credential; // ... }) .catch((error) => { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; // ... });
Eseguire l'autenticazione con Firebase in un'estensione di Chrome
Se stai creando un'app di estensione di Chrome, consulta la guida ai documenti off-screen.
Passaggi successivi
Dopo il primo accesso di un utente, viene creato un nuovo account utente e collegato alle credenziali, ovvero nome utente e password, numero di telefono o informazioni del fornitore di autenticazione, con cui l'utente ha eseguito l'accesso. Questo nuovo account viene memorizzato come parte del tuo progetto Firebase e può essere utilizzato per identificare un utente in ogni app del tuo progetto, indipendentemente dalla modalità di accesso.
-
Nelle tue app, il modo consigliato per conoscere lo stato di autenticazione dell'utente è impostare un observer sull'oggetto
Auth. Puoi quindi ottenere le informazioni di base del profilo dell'utente dall'oggettoUser. Vedi Gestire gli utenti. Nelle regole di sicurezza di Firebase Realtime Database e Cloud Storage, puoi ottenere l'ID utente univoco dell'utente che ha eseguito l'accesso dalla variabile
authe utilizzarlo per controllare a quali dati può accedere un utente.
Puoi consentire agli utenti di accedere alla tua app utilizzando più provider di autenticazione collegando le credenziali del provider di autenticazione a un account utente esistente.
Per disconnettere un utente, chiama
signOut:
Web
import { getAuth, signOut } from "firebase/auth"; const auth = getAuth(); signOut(auth).then(() => { // Sign-out successful. }).catch((error) => { // An error happened. });
Web
firebase.auth().signOut().then(() => { // Sign-out successful. }).catch((error) => { // An error happened. });