Einige Aktionen zur Nutzerverwaltung, z. B. das Aktualisieren der E-Mail-Adresse eines Nutzers und das Zurücksetzen des Passworts eines Nutzers, führen dazu, dass E-Mails an den Nutzer gesendet werden. Diese E-Mails enthalten Links, die Empfänger öffnen können, um die Nutzerverwaltungsaktion abzuschließen oder abzubrechen. Standardmäßig verweisen E-Mails zur Nutzerverwaltung auf den Standard-Aktions-Handler. 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-Aktions-Handler erstellen und hosten, um eine benutzerdefinierte Verarbeitung durchzuführen und den E-Mail-Aktions-Handler in Ihre Website einzubinden.
Für die folgenden Aktionen zur Nutzerverwaltung muss der Nutzer die Aktion über einen E-Mail-Aktions-Handler ausführen:
- Passwörter zurücksetzen
- Änderungen der E-Mail-Adresse widerrufen: Wenn Nutzer die primäre E-Mail-Adresse ihres Kontos ändern, sendet Firebase eine E-Mail an die alte Adresse, über die sie die Änderung rückgängig machen können.
- E‑Mail-Adressen werden überprüft
Wenn Sie den E-Mail-Aktions-Handler Ihres Firebase-Projekts anpassen möchten, müssen Sie eine Webseite erstellen und hosten, die das Firebase JavaScript SDK verwendet, um die Gültigkeit der Anfrage zu prüfen und die Anfrage abzuschließen. Anschließend müssen Sie die E-Mail-Vorlagen Ihres Firebase-Projekts so anpassen, dass sie auf Ihren benutzerdefinierten Aktions-Handler verweisen.
Seite für den E-Mail-Aktions-Handler erstellen
Firebase fügt der URL des Aktions-Handlers mehrere Suchparameter hinzu, wenn E-Mails zur Nutzerverwaltung generiert werden. Beispiel:
https://example.com/usermgmt?mode=resetPassword&oobCode=ABC123&apiKey=AIzaSy...&lang=fr
Diese Parameter geben die Nutzerverwaltungsaufgabe an, die der Nutzer ausführt. Die Seite für den E-Mail-Aktions-Handler muss die folgenden Suchparameter verarbeiten:
Parameter Modus Die auszuführende Nutzerverwaltungsaktion. Kann einen der folgenden Werte haben:
resetPasswordrecoverEmailverifyEmail
oobCode Ein Einmalcode, der zur Identifizierung und Bestätigung einer Anfrage verwendet wird apiKey Der API-Schlüssel Ihres Firebase-Projekts, der zur Vereinfachung bereitgestellt wird 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 „Passwort zurücksetzen“ und „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 Weiterleitungs-URL angegeben werden, damit diese verfügbar ist. So können Nutzer nach einer E-Mail-Aktion genau dort weitermachen, wo sie aufgehört haben.lang Dies ist das optionale BCP47-Sprach-Tag, das die Spracheinstellung des Nutzers darstellt (z. B.
fr). Sie können diesen Wert verwenden, um Ihren Nutzern lokalisierte Seiten für die Verarbeitung von E-Mail-Aktionen bereitzustellen.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';.Damit die Nutzererfahrung einheitlich ist, muss die Lokalisierung des Handlers für E-Mail-Aktionen mit der der E-Mail-Vorlage übereinstimmen.
Das folgende Beispiel zeigt, wie Sie die Suchparameter 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);
Anfragen zum Zurücksetzen des Passworts werden verarbeitet, indem zuerst der Aktionscode mit
verifyPasswordResetCodeverifiziert wird. Anschließend wird ein neues Passwort vom Nutzer abgerufen und anconfirmPasswordResetübergeben. 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. }); }
Widerrufe von E-Mail-Adressänderungen können Sie verarbeiten, indem Sie zuerst den Aktionscode mit
checkActionCodeprüfen 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. }); }
Führen Sie die Bestätigung der E-Mail-Adresse durch, indem Sie eine Bestätigungsschaltfläche anzeigen und einen Klick des Nutzers anfordern, bevor Sie
applyActionCodeaufrufen. Wenn ein Nutzerklick erforderlich ist, wird verhindert, dass automatisierte E‑Mail-Sicherheitsscanner, die Links vorab abrufen, einmalige Bestätigungscodes einlösen, bevor der Nutzer die Seite öffnet: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. }); }); }Hosten Sie die Seite, z. B. mit Firebase Hosting.
Fehlerbehebung: Veralteter oder ungültiger API-Schlüssel in Aktionslinks
Das Firebase Authentication-Backend verwaltet den API-Schlüssel, der in die generierten Aktionslinks eingebettet ist, z. B. den Parameter apiKey in der URL. Wenn Sie die API-Schlüssel Ihres Projekts rotieren oder den Schlüssel löschen, der ursprünglich mit Firebase Auth verknüpft war, erhalten Ihre Nutzer möglicherweise Links mit ungültigen Schlüsseln, was zu auth/invalid-api-key-Fehlern führt.
So beheben Sie dies:
- Wenn Sie Firebase Hosting verwenden: Der API-Schlüssel wird möglicherweise in
init.jsonim Cache gespeichert. Stellen Sie eine neue Version Ihrer Hosting-Website (firebase deploy --only hosting) bereit, um den Backend-Metadatendienst zu zwingen, die Konfiguration mit dem aktiven API-Schlüssel neu zu generieren. - Wenn der Backend-Schlüssel selbst aktualisiert werden muss: Da die Zuordnung des Backend-API-Schlüssels nicht direkt über die Console oder SDKs geändert werden kann, müssen Sie sich an den Support wenden, um eine Aktualisierung der Backend-Authentifizierungskonfiguration für Ihr Projekt anzufordern.
Als Nächstes müssen Sie Ihr Firebase-Projekt so konfigurieren, dass es in den E-Mails zur Nutzerverwaltung mit Ihrem benutzerdefinierten E-Mail-Aktions-Handler verknüpft wird.
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 in 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 den benutzerdefinierten E-Mail-Aktions-Handler an.
Nachdem Sie die URL gespeichert haben, wird sie von allen E-Mail-Vorlagen Ihres Firebase-Projekts verwendet.