Alcune azioni di gestione utenti, come l'aggiornamento dell'indirizzo email di un utente e la reimpostazione della password di un utente, comportano l'invio di email all'utente. Queste email contengono link che i destinatari possono aprire per completare o annullare l'azione di gestione degli utenti. Per impostazione predefinita, le email di gestione degli utenti rimandano al gestore delle azioni predefinito, ovvero una pagina web ospitata su un URL nel dominio Firebase Hosting del progetto.
In alternativa, puoi creare e ospitare un gestore di azioni email personalizzato per eseguire l'elaborazione personalizzata e integrare il gestore di azioni email con il tuo sito web.
Le seguenti azioni di gestione degli utenti richiedono che l'utente completi l'azione utilizzando un gestore delle azioni email:
- Reimpostazione delle password
- Revoca delle modifiche all'indirizzo email: quando gli utenti modificano l'indirizzo email principale dei loro account, Firebase invia un'email ai loro vecchi indirizzi per consentire loro di annullare la modifica
- Verifica degli indirizzi email
Per personalizzare il gestore delle azioni email del tuo progetto Firebase, devi creare e ospitare una pagina web che utilizzi l'SDK Firebase JavaScript per verificare la validità della richiesta e completarla. Poi, devi personalizzare i modelli di email del tuo progetto Firebase per collegarli al gestore delle azioni personalizzate.
Crea la pagina del gestore delle azioni email
Firebase aggiunge diversi parametri di query all'URL del gestore delle azioni quando genera email di gestione degli utenti. Ad esempio:
https://example.com/usermgmt?mode=resetPassword&oobCode=ABC123&apiKey=AIzaSy...&lang=fr
Questi parametri specificano l'attività di gestione utenti che l'utente sta completando. La pagina del gestore delle azioni email deve gestire i seguenti parametri di query:
Parametri modalità L'azione di gestione utenti da completare. Può essere uno dei seguenti valori:
resetPasswordrecoverEmailverifyEmail
oobCode Un codice monouso utilizzato per identificare e verificare una richiesta apiKey La chiave API del tuo progetto Firebase, fornita per comodità continueUrl Questo è un URL facoltativo che consente di passare lo stato all'app tramite un URL. Questo è pertinente per le modalità di reimpostazione password e di verifica email. Quando invii un'email di reimpostazione password o un'email di verifica, è necessario specificare un oggetto ActionCodeSettingscon un URL continuo affinché sia disponibile. In questo modo, un utente può continuare esattamente da dove aveva interrotto dopo un'azione via email.lang Questo è il tag di lingua BCP47 facoltativo che rappresenta le impostazioni internazionali dell'utente (ad esempio,
fr). Puoi utilizzare questo valore per fornire agli utenti pagine di gestione delle azioni email localizzate.La localizzazione può essere impostata tramite la console Firebase o dinamicamente chiamando l'API client corrispondente prima di attivare l'azione email. Ad esempio, utilizzando JavaScript:
firebase.auth().languageCode = 'fr';.Per un'esperienza utente coerente, assicurati che la localizzazione del gestore delle azioni email corrisponda a quella del modello di email.
L'esempio seguente mostra come gestire i parametri di query in un gestore basato su browser. Puoi anche implementare il gestore come applicazione Node.js utilizzando una logica simile.
Web
import { initializeApp } from "firebase/app"; import { getAuth } from "firebase/auth"; document.addEventListener('DOMContentLoaded', () => { // TODO: Implement getParameterByName() // Get the action to complete. const mode = getParameterByName('mode'); // Get the one-time code from the query parameter. const actionCode = getParameterByName('oobCode'); // (Optional) Get the continue URL from the query parameter if available. const continueUrl = getParameterByName('continueUrl'); // (Optional) Get the language code if available. const lang = getParameterByName('lang') || 'en'; // Configure the Firebase SDK. // This is the minimum configuration required for the API to be used. const config = { 'apiKey': "YOUR_API_KEY" // Copy this key from the web initialization // snippet found in the Firebase console. }; const app = initializeApp(config); const auth = getAuth(app); // Handle the user management action. switch (mode) { case 'resetPassword': // Display reset password handler and UI. handleResetPassword(auth, actionCode, continueUrl, lang); break; case 'recoverEmail': // Display email recovery handler and UI. handleRecoverEmail(auth, actionCode, lang); break; case 'verifyEmail': // Display email verification handler and UI. handleVerifyEmail(auth, actionCode, continueUrl, lang); break; default: // Error: invalid mode. } }, false);
Web
document.addEventListener('DOMContentLoaded', () => { // TODO: Implement getParameterByName() // Get the action to complete. var mode = getParameterByName('mode'); // Get the one-time code from the query parameter. var actionCode = getParameterByName('oobCode'); // (Optional) Get the continue URL from the query parameter if available. var continueUrl = getParameterByName('continueUrl'); // (Optional) Get the language code if available. var lang = getParameterByName('lang') || 'en'; // Configure the Firebase SDK. // This is the minimum configuration required for the API to be used. var config = { 'apiKey': "YOU_API_KEY" // Copy this key from the web initialization // snippet found in the Firebase console. }; var app = firebase.initializeApp(config); var auth = app.auth(); // Handle the user management action. switch (mode) { case 'resetPassword': // Display reset password handler and UI. handleResetPassword(auth, actionCode, continueUrl, lang); break; case 'recoverEmail': // Display email recovery handler and UI. handleRecoverEmail(auth, actionCode, lang); break; case 'verifyEmail': // Display email verification handler and UI. handleVerifyEmail(auth, actionCode, continueUrl, lang); break; default: // Error: invalid mode. } }, false);
Gestisci le richieste di reimpostazione della password verificando prima il codice di azione con
verifyPasswordResetCode; quindi ottieni una nuova password dall'utente e passala aconfirmPasswordReset. Ad esempio:Web
import { verifyPasswordResetCode, confirmPasswordReset } from "firebase/auth"; function handleResetPassword(auth, actionCode, continueUrl, lang) { // Localize the UI to the selected language as determined by the lang // parameter. // Verify the password reset code is valid. verifyPasswordResetCode(auth, actionCode).then((email) => { const accountEmail = email; // TODO: Show the reset screen with the user's email and ask the user for // the new password. const newPassword = "..."; // Save the new password. confirmPasswordReset(auth, actionCode, newPassword).then((resp) => { // Password reset has been confirmed and new password updated. // TODO: Display a link back to the app, or sign-in the user directly // if the page belongs to the same domain as the app: // auth.signInWithEmailAndPassword(accountEmail, newPassword); // TODO: If a continue URL is available, display a button which on // click redirects the user back to the app via continueUrl with // additional state determined from that URL's parameters. }).catch((error) => { // Error occurred during confirmation. The code might have expired or the // password is too weak. }); }).catch((error) => { // Invalid or expired action code. Ask user to try to reset the password // again. }); }
Web
function handleResetPassword(auth, actionCode, continueUrl, lang) { // Localize the UI to the selected language as determined by the lang // parameter. // Verify the password reset code is valid. auth.verifyPasswordResetCode(actionCode).then((email) => { var accountEmail = email; // TODO: Show the reset screen with the user's email and ask the user for // the new password. var newPassword = "..."; // Save the new password. auth.confirmPasswordReset(actionCode, newPassword).then((resp) => { // Password reset has been confirmed and new password updated. // TODO: Display a link back to the app, or sign-in the user directly // if the page belongs to the same domain as the app: // auth.signInWithEmailAndPassword(accountEmail, newPassword); // TODO: If a continue URL is available, display a button which on // click redirects the user back to the app via continueUrl with // additional state determined from that URL's parameters. }).catch((error) => { // Error occurred during confirmation. The code might have expired or the // password is too weak. }); }).catch((error) => { // Invalid or expired action code. Ask user to try to reset the password // again. }); }
Gestisci le revoche delle modifiche degli indirizzi email verificando prima il codice azione con
checkActionCode, quindi ripristina l'indirizzo email dell'utente conapplyActionCode. Ad esempio:Web
import { checkActionCode, applyActionCode, sendPasswordResetEmail } from "firebase/auth"; function handleRecoverEmail(auth, actionCode, lang) { // Localize the UI to the selected language as determined by the lang // parameter. let restoredEmail = null; // Confirm the action code is valid. checkActionCode(auth, actionCode).then((info) => { // Get the restored email address. restoredEmail = info['data']['email']; // Revert to the old email. return applyActionCode(auth, actionCode); }).then(() => { // Account email reverted to restoredEmail // TODO: Display a confirmation message to the user. // You might also want to give the user the option to reset their password // in case the account was compromised: sendPasswordResetEmail(auth, restoredEmail).then(() => { // Password reset confirmation sent. Ask user to check their email. }).catch((error) => { // Error encountered while sending password reset code. }); }).catch((error) => { // Invalid code. }); }
Web
function handleRecoverEmail(auth, actionCode, lang) { // Localize the UI to the selected language as determined by the lang // parameter. var restoredEmail = null; // Confirm the action code is valid. auth.checkActionCode(actionCode).then((info) => { // Get the restored email address. restoredEmail = info['data']['email']; // Revert to the old email. return auth.applyActionCode(actionCode); }).then(() => { // Account email reverted to restoredEmail // TODO: Display a confirmation message to the user. // You might also want to give the user the option to reset their password // in case the account was compromised: auth.sendPasswordResetEmail(restoredEmail).then(() => { // Password reset confirmation sent. Ask user to check their email. }).catch((error) => { // Error encountered while sending password reset code. }); }).catch((error) => { // Invalid code. }); }
Gestisci la verifica dell'indirizzo email mostrando un pulsante di conferma e richiedendo un clic da parte dell'utente prima di chiamare
applyActionCode. La richiesta di un clic da parte dell'utente impedisce agli scanner di sicurezza delle email automatici che precaricano i link di utilizzare i codici di verifica una tantum prima che l'utente apra la pagina:Web
import { applyActionCode } from "firebase/auth"; function handleVerifyEmail(auth, actionCode, continueUrl, lang) { // Localize the UI to the selected language as determined by the lang // parameter. // Show the confirmation button and apply the action code only after // the user clicks it. const confirmButton = document.getElementById('confirm-verify-email'); if (!confirmButton) { return; } confirmButton.hidden = false; confirmButton.addEventListener('click', () => { confirmButton.disabled = true; applyActionCode(auth, actionCode).then(() => { // Email address has been verified. Display a confirmation // message, and if continueUrl is available, provide a button // that redirects back to the app. }).catch((error) => { confirmButton.disabled = false; // Code is invalid, expired, or failed due to a network error. // Ask the user to verify their email address again if needed. }); }); }Web
function handleVerifyEmail(auth, actionCode, continueUrl, lang) { // Localize the UI to the selected language as determined by the lang // parameter. // Show the confirmation button and apply the action code only after // the user clicks it. var confirmButton = document.getElementById('confirm-verify-email'); if (!confirmButton) { return; } confirmButton.hidden = false; confirmButton.addEventListener('click', function() { confirmButton.disabled = true; auth.applyActionCode(actionCode).then(function() { // Email address has been verified. Display a confirmation // message, and if continueUrl is available, provide a button // that redirects back to the app. }).catch(function(error) { confirmButton.disabled = false; // Code is invalid, expired, or failed due to a network error. // Ask the user to verify their email address again if needed. }); }); }Ospita la pagina da qualche parte, ad esempio utilizza Firebase Hosting.
Risoluzione dei problemi: chiave API obsoleta o non valida nei link all'azione
Il backend di Firebase Authentication gestisce la chiave API incorporata nei link all'azione generati, ad esempio il parametro apiKey nell'URL. Se ruoti
le chiavi API del progetto o elimini la chiave originariamente associata a
Firebase Auth, i tuoi utenti potrebbero ricevere link con chiavi non valide, con conseguenti
errori auth/invalid-api-key.
Per risolvere questo problema:
- Se utilizzi Firebase Hosting: la chiave API potrebbe essere memorizzata nella cache in
init.json. Esegui il deployment di una nuova versione del tuo sito di Hosting (firebase deploy --only hosting) per forzare il servizio di metadati del backend a rigenerare la configurazione con la chiave API attiva. - Se è necessario aggiornare la chiave di backend stessa: poiché la mappatura della chiave API di backend non può essere modificata direttamente utilizzando la console o gli SDK, devi contattare l'assistenza per richiedere un aggiornamento della configurazione di autenticazione di backend per il tuo progetto.
Successivamente, devi configurare il progetto Firebase in modo che si colleghi al gestore di azioni email personalizzato nelle email di Gestione utenti.
Inserisci un link al tuo gestore personalizzato nei modelli di email
Per configurare il tuo progetto Firebase in modo che utilizzi il gestore di azioni email personalizzato:
Nella console Firebase, vai a Sicurezza > Autenticazione > scheda Modelli.
In una qualsiasi delle voci Tipi di email, fai clic sull'icona a forma di matita per modificare il modello di email.
Fai clic su Personalizza URL azione e specifica l'URL del gestore delle azioni email personalizzate.
Dopo aver salvato l'URL, questo verrà utilizzato da tutti i modelli di email del tuo progetto Firebase.