Bei einigen Nutzerverwaltungsaktionen, z. B. beim Aktualisieren der E-Mail-Adresse eines Nutzers und beim Zurücksetzen des Passworts eines Nutzers, werden E-Mails an den Nutzer gesendet. Diese E‑Mails enthalten Links, die Empfänger öffnen können, um die Nutzerverwaltungsaktion abzuschließen oder abzubrechen. Standardmäßig werden E‑Mails zur Nutzerverwaltung mit dem Standard-Aktionshandler verknüpft. Das ist eine Webseite, die unter einer URL in der Firebase Hosting-Domain Ihres Projekts gehostet wird.
Stattdessen können Sie einen benutzerdefinierten E‑Mail-Aktionshandler erstellen und hosten, um benutzerdefinierte Verarbeitungsschritte auszuführen und den E‑Mail-Aktionshandler in Ihre Website einzubinden.
Für die folgenden Nutzerverwaltungsaktionen muss der Nutzer die Aktion über einen E‑Mail-Aktionshandler ausführen:
- Passwörter zurücksetzen
- Änderungen der E‑Mail-Adresse widerrufen: Wenn Nutzer die primären E‑Mail-Adressen ihrer Konten ändern, sendet Firebase eine E‑Mail an ihre alten Adressen, über die sie die Änderung rückgängig machen können.
- E-Mail-Adressen bestätigen
Wenn Sie den E-Mail-Aktionshandler Ihres Firebase-Projekts anpassen möchten, müssen Sie eine Webseite erstellen und hosten, auf der das Firebase JavaScript SDK verwendet wird, um die Gültigkeit der Anfrage zu bestätigen und die Anfrage abzuschließen. Anschließend müssen Sie die E‑Mail-Vorlagen Ihres Firebase-Projekts anpassen, damit sie auf Ihren benutzerdefinierten Aktions-Handler verweisen.
Seite für den E-Mail-Aktions-Handler erstellen
Firebase fügt der URL des Aktionshandlers mehrere Suchparameter hinzu, wenn E-Mails zur Nutzerverwaltung generiert werden. Beispiel:
https://example.com/usermgmt?mode=resetPassword&oobCode=ABC123&apiKey=AIzaSy...&lang=fr
Mit diesen Parametern wird die Nutzerverwaltungsaufgabe angegeben, die der Nutzer ausführt. Ihre E‑Mail-Aktionshandler-Seite muss die folgenden Abfrageparameter verarbeiten:
Parameter Modus Die auszuführende Nutzerverwaltungsaktion. Mögliche Werte:
resetPasswordrecoverEmailverifyEmail
oobCode Ein Einmal-Code, mit dem eine Anfrage identifiziert und bestätigt wird apiKey Der API-Schlüssel Ihres Firebase-Projekts (wird zur Vereinfachung angegeben) continueUrl Dies ist eine optionale URL, über die der Status über eine URL an die App zurückgegeben werden kann. Dies ist für die Modi zum Zurücksetzen des Passworts und zur E-Mail-Bestätigung relevant. Wenn Sie eine E‑Mail zum Zurücksetzen des Passworts oder eine Bestätigungs-E‑Mail senden, muss ein ActionCodeSettings-Objekt mit einer „continue“-URL angegeben werden, damit diese verfügbar ist. So kann ein Nutzer nach einer E‑Mail-Aktion genau dort weitermachen, wo er aufgehört hat.lang Dies ist das optionale BCP47-Sprachtag , das das Gebietsschema des Nutzers darstellt (z. B.
fr). Sie können diesen Wert verwenden, um Ihren Nutzern lokalisierte E-Mail-Aktionshandler-Seiten zur Verfügung zu stellen.Die Lokalisierung kann über die Firebase Console oder dynamisch durch Aufrufen der entsprechenden Client-API vor dem Auslösen der E-Mail-Aktion festgelegt werden. Beispiel mit JavaScript:
firebase.auth().languageCode = 'fr';.Achten Sie für eine einheitliche Nutzererfahrung darauf, dass die Lokalisierung des E-Mail-Aktionshandlers mit der der E-Mail-Vorlage übereinstimmt.
Das folgende Beispiel zeigt, wie Sie die Abfrageparameter in einem browserbasierten Handler verarbeiten können. Sie können den Handler auch als Node.js-Anwendung mit ähnlicher Logik implementieren.
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);
Verarbeiten Sie Anfragen zum Zurücksetzen des Passworts, indem Sie zuerst den Aktionscode mit
verifyPasswordResetCodebestätigen. Rufen Sie dann ein neues Passwort vom Nutzer ab und übergeben Sie es anconfirmPasswordReset. Beispiel: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. }); }
Gehen Sie bei der Aufhebung von Änderungen der E-Mail-Adresse so vor, dass Sie zuerst den Aktionscode mit
checkActionCodebestätigen und dann die E-Mail-Adresse des Nutzers mitapplyActionCodewiederherstellen. Beispiel: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. }); }
Die Bestätigung der E-Mail-Adresse erfolgt durch Aufrufen von
applyActionCode. Beispiel:Web
function handleVerifyEmail(auth, actionCode, continueUrl, lang) { // Localize the UI to the selected language as determined by the lang // parameter. // Try to apply the email verification code. applyActionCode(auth, actionCode).then((resp) => { // Email address has been verified. // TODO: Display a confirmation message to the user. // You could also provide the user with a link back to the app. // 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) => { // Code is invalid or expired. Ask the user to verify their email address // again. }); }
Web
function handleVerifyEmail(auth, actionCode, continueUrl, lang) { // Localize the UI to the selected language as determined by the lang // parameter. // Try to apply the email verification code. auth.applyActionCode(actionCode).then((resp) => { // Email address has been verified. // TODO: Display a confirmation message to the user. // You could also provide the user with a link back to the app. // 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) => { // Code is invalid or expired. Ask the user to verify their email address // again. }); }
Hosten Sie die Seite irgendwo, z. B. mit Firebase Hosting.
Als Nächstes müssen Sie Ihr Firebase-Projekt so konfigurieren, dass es in den E-Mails zur Nutzerverwaltung auf Ihren benutzerdefinierten E-Mail-Aktionshandler verweist.
Link zu Ihrem benutzerdefinierten Handler in Ihren E‑Mail-Vorlagen
So konfigurieren Sie Ihr Firebase-Projekt für die Verwendung Ihres benutzerdefinierten E-Mail-Aktions-Handlers:
Rufen Sie in der Firebase-Konsole den Tab Sicherheit > Authentifizierung > Vorlagen auf.
Klicken Sie bei einem der Einträge unter E-Mail-Typen auf das Stiftsymbol, um die E-Mail-Vorlage zu bearbeiten.
Klicken Sie auf Aktions-URL anpassen und geben Sie die URL für Ihren benutzerdefinierten E-Mail-Aktions-Handler an.
Nachdem Sie die URL gespeichert haben, wird sie für alle E-Mail-Vorlagen Ihres Firebase-Projekts verwendet.