אימות באמצעות Firebase באמצעות קישור לאימייל ב-JavaScript

אתם יכולים להשתמש באימות ב-Firebase כדי לאפשר למשתמשים להיכנס לחשבון באמצעות קישור שנשלח באימייל. במהלך התהליך, גם כתובת האימייל של המשתמש מאומתת.

יש הרבה יתרונות לכניסה באמצעות כתובת אימייל:

  • הרשמה וכניסה בקלות.
  • סיכון נמוך יותר לשימוש חוזר בסיסמאות באפליקציות שונות, שעלול לפגוע באבטחה גם של סיסמאות שנבחרו בקפידה.
  • היכולת לאמת משתמש וגם לוודא שהוא הבעלים החוקי של כתובת אימייל.
  • כדי להיכנס, המשתמשים צריכים רק חשבון אימייל נגיש. לא צריך להיות בעלים של מספר טלפון או חשבון ברשתות החברתיות.
  • המשתמשים יכולים להיכנס לחשבון בצורה מאובטחת בלי להזין (או לזכור) סיסמה, מה שיכול להיות מסורבל במכשיר נייד.
  • משתמש קיים שנכנס בעבר באמצעות מזהה אימייל (סיסמה או מאוחד) יכול לשדרג את הכניסה שלו כך שיוכל להיכנס באמצעות האימייל בלבד. לדוגמה, משתמש ששכח את הסיסמה שלו עדיין יכול להיכנס בלי לאפס את הסיסמה.

לפני שמתחילים

אם עדיין לא עשיתם את זה, העתיקו את קטע הקוד של האיניציאליזציה ממסוף Firebase לפרויקט, כמו שמתואר במאמר הוספת Firebase לפרויקט JavaScript.

כדי לאפשר למשתמשים להיכנס באמצעות קישור באימייל, קודם צריך להפעיל את ספק האימייל ואת שיטת הכניסה לחשבון באמצעות קישור באימייל בפרויקט Firebase:

  1. במסוף Firebase, נכנסים לאבטחה > אימות.

  2. בכרטיסייה Sign-in method, מפעילים את שיטת הכניסה לחשבון Email/Password. שימו לב: כדי להשתמש בכניסה באמצעות קישור באימייל, צריך להפעיל את הכניסה באמצעות אימייל/סיסמה.

  3. באותו קטע, מפעילים את ספק הכניסה Email link (passwordless sign-in).

  4. לוחצים על שמירה.

כדי להתחיל את תהליך האימות, מציגים למשתמש ממשק שמבקש ממנו לספק את כתובת האימייל שלו, ואז קוראים ל-sendSignInLinkToEmail כדי לבקש מ-Firebase לשלוח את קישור האימות לכתובת האימייל של המשתמש.

  1. יוצרים את האובייקט ActionCodeSettings, שמספק ל-Firebase הוראות ליצירת הקישור לאימייל. מגדירים את השדות הבאים:

    • ‫url: קישור העומק להטמעה וכל מצב נוסף שצריך להעביר. אם עדיין לא עשיתם את זה, הוסיפו את הדומיין שלכם לרשימת הדומיינים המורשים:

      1. במסוף Firebase, נכנסים לכרטיסייה Security ‏> Authentication ‏> Settings.

      2. בקטע Authorized domains, לוחצים על Add domain ומוסיפים את הדומיין.

    • ‫android ו-ios: עוזרים ל-Firebase Authentication לקבוע אם ליצור קישור לאינטרנט בלבד או קישור לנייד שנפתח במכשיר Android או Apple.
    • handleCodeInApp: מוגדר ל-true. בניגוד לפעולות אחרות שמתבצעות מחוץ לאפליקציה (איפוס סיסמה ואימות אימייל), את פעולת הכניסה תמיד צריך להשלים באפליקציה. הסיבה לכך היא שבסוף התהליך, המשתמש אמור להיות מחובר ומצב האימות שלו נשמר באפליקציה.
    • linkDomain: כשמגדירים לפרויקט דומיינים מותאמים אישית לקישורים ב-Hosting, צריך לציין באיזה דומיין להשתמש כשהקישור נפתח באפליקציה ספציפית לנייד. אחרת, דומיין ברירת המחדל נבחר באופן אוטומטי (לדוגמה, PROJECT_ID.firebaseapp.com).
    • ‫dynamicLinkDomain: הוצא משימוש. אל תציינו את הפרמטר הזה.

      Web

      const actionCodeSettings = {
        // URL you want to redirect back to. The domain (www.example.com) for this
        // URL must be in the authorized domains list in the Firebase Console.
        url: 'https://www.example.com/finishSignUp?cartId=1234',
        // This must be true.
        handleCodeInApp: true,
        iOS: {
          bundleId: 'com.example.ios'
        },
        android: {
          packageName: 'com.example.android',
          installApp: true,
          minimumVersion: '12'
        },
        // The domain must be configured in Firebase Hosting and owned by the project.
        linkDomain: 'custom-domain.com'
      };

      Web

      var actionCodeSettings = {
        // URL you want to redirect back to. The domain (www.example.com) for this
        // URL must be in the authorized domains list in the Firebase Console.
        url: 'https://www.example.com/finishSignUp?cartId=1234',
        // This must be true.
        handleCodeInApp: true,
        iOS: {
          bundleId: 'com.example.ios'
        },
        android: {
          packageName: 'com.example.android',
          installApp: true,
          minimumVersion: '12'
        },
        dynamicLinkDomain: 'example.page.link'
      };

    מידע נוסף על ActionCodeSettings זמין בקטע העברת מצב בפעולות באימייל.

  2. מבקשים מהמשתמש את כתובת האימייל שלו.

  3. שולחים את קישור האימות לכתובת האימייל של המשתמש ושומרים את כתובת האימייל של המשתמש למקרה שהוא ישלים את הכניסה באמצעות האימייל באותו מכשיר.

    Web

    import { getAuth, sendSignInLinkToEmail } from "firebase/auth";
    
    const auth = getAuth();
    sendSignInLinkToEmail(auth, email, actionCodeSettings)
      .then(() => {
        // The link was successfully sent. Inform the user.
        // Save the email locally so you don't need to ask the user for it again
        // if they open the link on the same device.
        window.localStorage.setItem('emailForSignIn', email);
        // ...
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        // ...
      });

    Web

    firebase.auth().sendSignInLinkToEmail(email, actionCodeSettings)
      .then(() => {
        // The link was successfully sent. Inform the user.
        // Save the email locally so you don't need to ask the user for it again
        // if they open the link on the same device.
        window.localStorage.setItem('emailForSignIn', email);
        // ...
      })
      .catch((error) => {
        var errorCode = error.code;
        var errorMessage = error.message;
        // ...
      });

בעיות אבטחה

כדי למנוע שימוש בקישור לכניסה לחשבון של משתמש לא מכוון או במכשיר לא מכוון, מערכת Firebase Auth דורשת לספק את כתובת האימייל של המשתמש כשמשלימים את תהליך הכניסה. כדי שהכניסה תצליח, כתובת האימייל הזו צריכה להיות זהה לכתובת שאליה נשלח הקישור לכניסה במקור.

כדי לייעל את התהליך הזה למשתמשים שפותחים את קישור הכניסה באותו מכשיר שבו הם ביקשו את הקישור, אתם יכולים לאחסן את כתובת האימייל שלהם באופן מקומי – למשל באמצעות localStorage או קובצי Cookie – כשאתם שולחים את הודעת האימייל לכניסה. אחר כך, משתמשים בכתובת הזו כדי להשלים את התהליך. אל תעבירו את כתובת האימייל של המשתמש בפרמטרים של כתובת ה-URL להפניה אוטומטית ואל תשתמשו בה שוב, כי זה עלול לאפשר הזרקות לסשן.

אחרי השלמת הכניסה, כל מנגנון כניסה קודם שלא אומת יוסר מהמשתמש וכל הסשנים הקיימים יבוטלו. לדוגמה, אם מישהו יצר בעבר חשבון לא מאומת עם אותה כתובת אימייל וסיסמה, הסיסמה של המשתמש תוסר כדי למנוע מהמתחזה שטען לבעלות ויצר את החשבון הלא מאומת להיכנס שוב עם כתובת האימייל והסיסמה הלא מאומתות.

בנוסף, חשוב להשתמש בכתובת URL מסוג HTTPS בסביבת הייצור כדי למנוע יירוט של הקישור על ידי שרתים מתווכים.

השלמת הכניסה לחשבון בדף אינטרנט

הפורמט של קישור העומק של הקישור באימייל זהה לפורמט שמשמש לפעולות אימייל מחוץ לתחום (אימות אימייל, איפוס סיסמה וביטול שינוי אימייל). Firebase Auth מפשט את הבדיקה הזו באמצעות ה-API של isSignInWithEmailLink, שבודק אם הקישור הוא קישור לכניסה באמצעות אימייל.

כדי להשלים את הכניסה בדף הנחיתה, צריך להפעיל את signInWithEmailLink עם כתובת האימייל של המשתמש והקישור בפועל לאימייל שמכיל את הקוד החד-פעמי.

Web

import { getAuth, isSignInWithEmailLink, signInWithEmailLink } from "firebase/auth";

// Confirm the link is a sign-in with email link.
const auth = getAuth();
if (isSignInWithEmailLink(auth, window.location.href)) {
  // Additional state parameters can also be passed via URL.
  // This can be used to continue the user's intended action before triggering
  // the sign-in operation.
  // Get the email if available. This should be available if the user completes
  // the flow on the same device where they started it.
  let email = window.localStorage.getItem('emailForSignIn');
  if (!email) {
    // User opened the link on a different device. To prevent session fixation
    // attacks, ask the user to provide the associated email again. For example:
    email = window.prompt('Please provide your email for confirmation');
  }
  // The client SDK will parse the code from the link for you.
  signInWithEmailLink(auth, email, window.location.href)
    .then((result) => {
      // Clear email from storage.
      window.localStorage.removeItem('emailForSignIn');
      // You can access the new user by importing getAdditionalUserInfo
      // and calling it with result:
      // getAdditionalUserInfo(result)
      // You can access the user's profile via:
      // getAdditionalUserInfo(result)?.profile
      // You can check if the user is new or existing:
      // getAdditionalUserInfo(result)?.isNewUser
    })
    .catch((error) => {
      // Some error occurred, you can inspect the code: error.code
      // Common errors could be invalid email and invalid or expired OTPs.
    });
}

Web

// Confirm the link is a sign-in with email link.
if (firebase.auth().isSignInWithEmailLink(window.location.href)) {
  // Additional state parameters can also be passed via URL.
  // This can be used to continue the user's intended action before triggering
  // the sign-in operation.
  // Get the email if available. This should be available if the user completes
  // the flow on the same device where they started it.
  var email = window.localStorage.getItem('emailForSignIn');
  if (!email) {
    // User opened the link on a different device. To prevent session fixation
    // attacks, ask the user to provide the associated email again. For example:
    email = window.prompt('Please provide your email for confirmation');
  }
  // The client SDK will parse the code from the link for you.
  firebase.auth().signInWithEmailLink(email, window.location.href)
    .then((result) => {
      // Clear email from storage.
      window.localStorage.removeItem('emailForSignIn');
      // You can access the new user via result.user
      // Additional user info profile not available via:
      // result.additionalUserInfo.profile == null
      // You can check if the user is new or existing:
      // result.additionalUserInfo.isNewUser
    })
    .catch((error) => {
      // Some error occurred, you can inspect the code: error.code
      // Common errors could be invalid email and invalid or expired OTPs.
    });
}

השלמת הכניסה לחשבון באפליקציה לנייד

‫Firebase Authentication משתמש ב-Firebase Hosting כדי לשלוח את הקישור באימייל למכשיר נייד. כדי להשלים את הכניסה דרך אפליקציה לנייד, צריך להגדיר את האפליקציה כך שתזהה את הקישור הנכנס לאפליקציה, תנתח את קישור העומק הבסיסי ואז תשלים את הכניסה כמו שנעשה דרך תהליך האינטרנט.

במדריך ל-Android מוסבר איך מטפלים בכניסה באמצעות קישור באימייל באפליקציה ל-Android.

במדריך לפלטפורמות של Apple מוסבר איך לטפל בכניסה באמצעות קישור באימייל באפליקציה של Apple.

אפשר גם לקשר את שיטת האימות הזו למשתמש קיים. לדוגמה, משתמש שאימת בעבר את הזהות שלו באמצעות ספק אחר, כמו מספר טלפון, יכול להוסיף את שיטת הכניסה הזו לחשבון הקיים שלו.

ההבדל יהיה בחצי השני של הפעולה:

Web

import { getAuth, linkWithCredential, EmailAuthProvider } from "firebase/auth";

// Construct the email link credential from the current URL.
const credential = EmailAuthProvider.credentialWithLink(
  email, window.location.href);

// Link the credential to the current user.
const auth = getAuth();
linkWithCredential(auth.currentUser, credential)
  .then((usercred) => {
    // The provider is now successfully linked.
    // The phone user can now sign in with their phone number or email.
  })
  .catch((error) => {
    // Some error occurred.
  });

Web

// Construct the email link credential from the current URL.
var credential = firebase.auth.EmailAuthProvider.credentialWithLink(
  email, window.location.href);

// Link the credential to the current user.
firebase.auth().currentUser.linkWithCredential(credential)
  .then((usercred) => {
    // The provider is now successfully linked.
    // The phone user can now sign in with their phone number or email.
  })
  .catch((error) => {
    // Some error occurred.
  });

אפשר להשתמש בזה גם כדי לאמת מחדש משתמש של קישור באימייל לפני שמבצעים פעולה רגישה.

Web

import { getAuth, reauthenticateWithCredential, EmailAuthProvider } from "firebase/auth";

// Construct the email link credential from the current URL.
const credential = EmailAuthProvider.credentialWithLink(
  email, window.location.href);

// Re-authenticate the user with this credential.
const auth = getAuth();
reauthenticateWithCredential(auth.currentUser, credential)
  .then((usercred) => {
    // The user is now successfully re-authenticated and can execute sensitive
    // operations.
  })
  .catch((error) => {
    // Some error occurred.
  });

Web

// Construct the email link credential from the current URL.
var credential = firebase.auth.EmailAuthProvider.credentialWithLink(
  email, window.location.href);

// Re-authenticate the user with this credential.
firebase.auth().currentUser.reauthenticateWithCredential(credential)
  .then((usercred) => {
    // The user is now successfully re-authenticated and can execute sensitive
    // operations.
  })
  .catch((error) => {
    // Some error occurred.
  });

עם זאת, יכול להיות שהתהליך לא יושלם כי הוא עלול להסתיים במכשיר אחר שבו המשתמש המקורי לא מחובר. במקרה כזה, אפשר להציג למשתמש שגיאה כדי לאלץ אותו לפתוח את הקישור באותו מכשיר. אפשר להעביר מצב מסוים בקישור כדי לספק מידע על סוג הפעולה ועל מזהה המשתמש.

אם יצרתם את הפרויקט ב-15 בספטמבר 2023 או אחרי התאריך הזה, ההגנה מפני ספירת כתובות אימייל מופעלת כברירת מחדל. התכונה הזו משפרת את האבטחה של חשבונות המשתמשים בפרויקט, אבל היא משביתה את השיטה fetchSignInMethodsForEmail(), שבעבר המלצנו להשתמש בה כדי להטמיע תהליכים שמתחילים בהזנת מזהה.

אפשר להשבית את ההגנה מפני ספירת אימיילים בפרויקט, אבל אנחנו לא ממליצים לעשות את זה.

לפרטים נוספים, קראו את המאמר הגנה מפני ספירת כתובות אימייל.

תבנית ברירת המחדל לאימייל לכניסה באמצעות קישור

תבנית ברירת המחדל של האימייל כוללת חותמת זמן בנושא ובתוכן האימייל, כדי שהאימיילים הבאים לא יכווצו לשרשור אחד והקישור יוסתר.

התבנית הזו רלוונטית לשפות הבאות:

קוד שפה
ar ערבית
zh-CN סינית (פשוטה)
zh-TW סינית (מסורתית)
nl הולנדית
en אנגלית
en-GB אנגלית (בריטניה)
fr צרפתית
de גרמנית
id [מזהה] אינדונזית
it איטלקי
ja יפנית
ko קוריאנית
pl פולנית
pt-BR פורטוגזית (ברזיל)
pt-PT פורטוגזית (פורטוגל)
ru רוסית
es ספרדית
es-419 ספרדית (אמריקה הלטינית)
th תאית

השלבים הבאים

אחרי שמשתמש נכנס לחשבון בפעם הראשונה, נוצר חשבון משתמש חדש שמקושר לפרטי הכניסה – כלומר, שם המשתמש והסיסמה, מספר הטלפון או פרטי ספק האימות – שאיתם המשתמש נכנס לחשבון. החשבון החדש הזה נשמר כחלק מהפרויקט ב-Firebase, ואפשר להשתמש בו כדי לזהות משתמש בכל אפליקציה בפרויקט, בלי קשר לאופן שבו המשתמש נכנס לחשבון.

  • באפליקציות, הדרך המומלצת לדעת את סטטוס האימות של המשתמש היא להגדיר משקיף באובייקט Auth. לאחר מכן תוכלו לקבל את פרטי הפרופיל הבסיסיים של המשתמש מהאובייקט User. ניהול משתמשים

  • בכללי האבטחה של Firebase Realtime Database ו-Cloud Storage, אפשר לקבל את מזהה המשתמש הייחודי של המשתמש המחובר מהמשתנה auth, ולהשתמש בו כדי לקבוע לאילו נתונים המשתמש יכול לגשת.

אתם יכולים לאפשר למשתמשים להיכנס לאפליקציה באמצעות כמה ספקי אימות, על ידי קישור פרטי הכניסה של ספק האימות לחשבון משתמש קיים.

כדי להוציא משתמש מהחשבון, מפעילים את 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.
});