Einige Aktionen zur Nutzerverwaltung, z. B. die Aktualisierung der E-Mail-Adresse eines Nutzers und das Zurücksetzen seines Passworts, führen dazu, dass E-Mails an den Nutzer gesendet werden. Diese E-Mails enthalten Links, über die die Empfänger die Nutzerverwaltungsaktion abschließen oder abbrechen können. Standardmäßig sind E-Mails zur Nutzerverwaltung mit dem Standard-Aktions-Handler verknüpft. Dabei handelt es sich um eine Webseite, die unter einer URL in der Firebase Hosting-Domain Ihres Projekts gehostet wird.
Sie können stattdessen 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.
Bei den folgenden Aktionen zur Nutzerverwaltung muss der Nutzer die Aktion mit einem E-Mail-Aktions-Handler ausführen:
- Passwörter zurücksetzen
- Widerruf von Änderungen an E-Mail-Adressen: Wenn Nutzer die primäre E-Mail-Adresse ihres Kontos ändern, sendet Firebase eine E-Mail an ihre alten Adressen, mit der sie die Änderung rückgängig machen können.
- E-Mail-Adressen bestätigen
Wenn Sie den E-Mail-Aktions-Handler Ihres Firebase-Projekts anpassen möchten, müssen Sie eine Webseite erstellen und hosten, auf der die Gültigkeit der Anfrage mithilfe des Firebase JavaScript SDK überprüft und die Anfrage abgeschlossen wird. Anschließend müssen Sie die E-Mail-Vorlagen Ihres Firebase-Projekts anpassen, um sie mit Ihrem benutzerdefinierten Aktions-Handler zu verknüpfen.
Seite für den E-Mail-Aktions-Handler erstellen
Firebase fügt Ihrer Action-Handler-URL 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 Aufgabe der Nutzerverwaltung an, die der Nutzer ausführt. Die Seite mit dem E-Mail-Aktions-Handler muss die folgenden Abfrageparameter verarbeiten:
Parameter Modus Die durchzuführende Nutzerverwaltungsaktion. Folgende Werte sind möglich:
resetPassword
recoverEmail
verifyEmail
oobCode Ein Einmalcode, mit dem eine Anfrage identifiziert und bestätigt wird apiKey Der API-Schlüssel Ihres Firebase-Projekts, der der Einfachheit halber bereitgestellt wird continueUrl Dies ist eine optionale URL, über die der Status über eine URL an die App zurückgegeben werden kann. Das gilt für die Modi „Passwort zurücksetzen“ und „E-Mail-Bestätigung“. Wenn Sie eine E-Mail zum Zurücksetzen des Passworts oder zur Bestätigung senden, muss ein ActionCodeSettings
-Objekt mit einer Weiterleitungs-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- Sprach-Tag, das die Sprache des Nutzers angibt (z. B.
fr
). Mit diesem Wert können Sie Ihren Nutzern lokalisierte Seiten für E-Mail-Aktions-Handler bereitstellen.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 in JavaScript:
firebase.auth().languageCode = 'fr';
.Achten Sie darauf, dass die Lokalisierung des E-Mail-Aktions-Handlers mit der der E-Mail-Vorlage übereinstimmt, damit die Nutzeroberfläche einheitlich ist.
Im folgenden Beispiel wird gezeigt, 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);
Verarbeite Anfragen zum Zurücksetzen des Passworts, indem du zuerst den Aktionscode bei
verifyPasswordResetCode
überprüfst. Fordere dann ein neues Passwort vom Nutzer an und leite es anconfirmPasswordReset
weiter. 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. }); }
Wenn du die E-Mail-Adresse eines Nutzers widerrufen möchtest, musst du zuerst den Aktionscode mit
checkActionCode
bestätigen und dann die E-Mail-Adresse des Nutzers mitapplyActionCode
wiederherstellen. 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. }); }
Rufen Sie
applyActionCode
an, um die Bestätigung der E-Mail-Adresse zu veranlassen. 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. unter Firebase Hosting.
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.
Verknüpfung mit Ihrem benutzerdefinierten Handler in Ihren E-Mail-Vorlagen
So konfigurieren Sie Ihr Firebase-Projekt für die Verwendung Ihres benutzerdefinierten E-Mail-Aktions-Handlers:
- Öffnen Sie Ihr Projekt in der Firebase Console.
- Rufen Sie im Bereich Authentifizierung die Seite E-Mail-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 von allen E-Mail-Vorlagen Ihres Firebase-Projekts verwendet.