ตรวจสอบสิทธิ์ด้วย Firebase โดยใช้ลิงก์อีเมลใน JavaScript

คุณสามารถใช้การตรวจสอบความถูกต้องของ Firebase เพื่อลงชื่อเข้าใช้ผู้ใช้โดยส่งอีเมลที่มีลิงก์ให้ผู้ใช้คลิกเพื่อลงชื่อเข้าใช้ ในขั้นตอนนี้ ที่อยู่อีเมลของผู้ใช้จะได้รับการยืนยันด้วย

มีประโยชน์มากมายในการลงชื่อเข้าใช้ด้วยอีเมล:

  • การลงทะเบียนและการลงชื่อเข้าใช้ที่มีแรงเสียดทานต่ำ
  • ลดความเสี่ยงของการใช้รหัสผ่านซ้ำในแอปพลิเคชัน ซึ่งอาจทำลายความปลอดภัยของรหัสผ่านที่เลือกมาอย่างดี
  • ความสามารถในการรับรองความถูกต้องของผู้ใช้ในขณะเดียวกันก็ยืนยันว่าผู้ใช้เป็นเจ้าของที่อยู่อีเมลที่ถูกต้องตามกฎหมาย
  • ผู้ใช้ต้องการเพียงบัญชีอีเมลที่สามารถเข้าถึงได้เพื่อลงชื่อเข้าใช้ ไม่จำเป็นต้องเป็นเจ้าของหมายเลขโทรศัพท์หรือบัญชีโซเชียลมีเดีย
  • ผู้ใช้สามารถลงชื่อเข้าใช้ได้อย่างปลอดภัยโดยไม่จำเป็นต้องระบุ (หรือจำ) รหัสผ่าน ซึ่งอาจเป็นเรื่องยุ่งยากบนอุปกรณ์พกพา
  • ผู้ใช้ปัจจุบันที่ลงชื่อเข้าใช้ด้วยตัวระบุอีเมล (รหัสผ่านหรือส่วนกลาง) สามารถอัปเกรดเพื่อลงชื่อเข้าใช้ด้วยอีเมลเพียงอย่างเดียว ตัวอย่างเช่น ผู้ใช้ที่ลืมรหัสผ่านยังสามารถลงชื่อเข้าใช้ได้โดยไม่จำเป็นต้องรีเซ็ตรหัสผ่าน

ก่อนที่คุณจะเริ่มต้น

หากคุณยังไม่ได้ดำเนินการ ให้คัดลอกข้อมูลโค้ดการเริ่มต้นจาก คอนโซล Firebase ไปยังโครงการของคุณตามที่อธิบายไว้ใน Add Firebase to your JavaScript project

ในการลงชื่อเข้าใช้ผู้ใช้ด้วยลิงก์อีเมล คุณต้องเปิดใช้ผู้ให้บริการอีเมลและวิธีการลงชื่อเข้าใช้ลิงก์อีเมลสำหรับโปรเจ็กต์ Firebase ของคุณก่อน:

  1. ใน คอนโซล Firebase ให้เปิดส่วน การรับรองความถูกต้อง
  2. บนแท็บ วิธีการลงชื่อเข้า ใช้ ให้เปิดใช้งานผู้ให้บริการ อีเมล/รหัสผ่าน โปรดทราบว่าต้องเปิดใช้งานการลงชื่อเข้าใช้ด้วยอีเมล/รหัสผ่านเพื่อใช้การลงชื่อเข้าใช้ด้วยลิงก์อีเมล
  3. ในส่วนเดียวกัน ให้เปิดใช้งานวิธีการลงชื่อเข้า ใช้ด้วยลิงก์อีเมล (ลงชื่อเข้าใช้แบบไม่ใช้รหัสผ่าน)
  4. คลิก บันทึก

ในการเริ่มต้นโฟลว์การตรวจสอบสิทธิ์ ให้แสดงอินเทอร์เฟซแก่ผู้ใช้ที่แจ้งให้ผู้ใช้ระบุที่อยู่อีเมล จากนั้นเรียก sendSignInLinkToEmail เพื่อขอให้ Firebase ส่งลิงก์การตรวจสอบสิทธิ์ไปยังอีเมลของผู้ใช้

  1. สร้างวัตถุ ActionCodeSettings ซึ่งให้ Firebase พร้อมคำแนะนำเกี่ยวกับวิธีสร้างลิงก์อีเมล ตั้งค่าฟิลด์ต่อไปนี้:

    • url : ลิงก์ในรายละเอียดเพื่อฝังและสถานะเพิ่มเติมที่จะส่งต่อ ต้องเพิ่มโดเมนของลิงก์ในรายการคอนโซล Firebase ของโดเมนที่ได้รับอนุญาต ซึ่งดูได้โดยไปที่แท็บวิธีการลงชื่อเข้าใช้ (การตรวจสอบสิทธิ์ -> วิธีการลงชื่อเข้าใช้)
    • android และ ios : แอพที่จะใช้เมื่อเปิดลิงค์ลงชื่อเข้าใช้บนอุปกรณ์ Android หรือ Apple เรียนรู้เพิ่มเติมเกี่ยวกับวิธี กำหนดค่า Firebase Dynamic Links เพื่อเปิดลิงก์การดำเนินการทางอีเมลผ่านแอปบนอุปกรณ์เคลื่อนที่
    • handleCodeInApp : ตั้งค่าเป็นจริง การดำเนินการลงชื่อเข้าใช้จะต้องเสร็จสิ้นในแอปเสมอซึ่งแตกต่างจากการดำเนินการทางอีเมลอื่น ๆ (การรีเซ็ตรหัสผ่านและการยืนยันอีเมล) นี่เป็นเพราะเมื่อสิ้นสุดโฟลว์ ผู้ใช้คาดว่าจะลงชื่อเข้าใช้และสถานะการรับรองความถูกต้องยังคงอยู่ในแอป
    • dynamicLinkDomain : เมื่อมีการกำหนดโดเมนลิงก์แบบไดนามิกที่กำหนดเองหลายโดเมนสำหรับโครงการ ให้ระบุว่าจะใช้โดเมนใดเมื่อจะเปิดลิงก์ผ่านแอปบนอุปกรณ์เคลื่อนที่ที่ระบุ (เช่น example.page.link ) มิฉะนั้น โดเมนแรกจะถูกเลือกโดยอัตโนมัติ

      Web modular API

      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'
        },
        dynamicLinkDomain: 'example.page.link'
      };

      Web namespaced API

      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 โปรดดูที่ Passing State ในส่วน Email Actions

  2. ขออีเมลจากผู้ใช้

  3. ส่งลิงก์การตรวจสอบสิทธิ์ไปยังอีเมลของผู้ใช้ และบันทึกอีเมลของผู้ใช้ในกรณีที่ผู้ใช้ลงชื่อเข้าใช้อีเมลในอุปกรณ์เดียวกัน

    Web modular API

    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 namespaced API

    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 หรือคุกกี้ เมื่อคุณส่งอีเมลลงชื่อเข้าใช้ จากนั้นใช้ที่อยู่นี้เพื่อดำเนินการตามขั้นตอน อย่าส่งต่ออีเมลของผู้ใช้ในพารามิเตอร์ URL เปลี่ยนเส้นทางและนำกลับมาใช้ใหม่ เนื่องจากอาจทำให้มีการแทรกเซสชันได้

หลังจากการลงชื่อเข้าใช้เสร็จสิ้น กลไกการลงชื่อเข้าใช้ที่ไม่ได้รับการตรวจสอบก่อนหน้านี้จะถูกลบออกจากผู้ใช้ และเซสชันที่มีอยู่จะใช้งานไม่ได้ ตัวอย่างเช่น หากก่อนหน้านี้มีคนสร้างบัญชีที่ไม่ผ่านการยืนยันด้วยอีเมลและรหัสผ่านเดิม รหัสผ่านของผู้ใช้จะถูกลบออกเพื่อป้องกันไม่ให้ผู้แอบอ้างที่อ้างสิทธิ์ความเป็นเจ้าของและสร้างบัญชีที่ไม่ผ่านการยืนยันนั้นลงชื่อเข้าใช้อีกครั้งด้วยอีเมลและรหัสผ่านที่ยังไม่ได้ยืนยัน

ตรวจสอบให้แน่ใจว่าคุณใช้ HTTPS URL ในการผลิตเพื่อหลีกเลี่ยงไม่ให้ลิงก์ของคุณถูกขัดขวางโดยเซิร์ฟเวอร์ตัวกลาง

เสร็จสิ้นการลงชื่อเข้าใช้ในหน้าเว็บ

รูปแบบของ Deep Link ของลิงก์อีเมลจะเหมือนกับ รูปแบบที่ใช้สำหรับการดำเนินการกับอีเมลนอกแบนด์ (การยืนยันอีเมล การรีเซ็ตรหัสผ่าน และการเพิกถอนการเปลี่ยนแปลงอีเมล) Firebase Auth ทำให้การตรวจสอบนี้ง่ายขึ้นด้วยการจัดเตรียม isSignInWithEmailLink API เพื่อตรวจสอบว่าลิงก์นั้นเป็นลิงก์ลงชื่อเข้าใช้ด้วยอีเมลหรือไม่

ในการลงชื่อเข้าใช้ในหน้า Landing Page ให้เสร็จสมบูรณ์ ให้โทรหา signInWithEmailLink ด้วยอีเมลของผู้ใช้และลิงก์อีเมลจริงที่มีรหัสแบบใช้ครั้งเดียว

Web modular API

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 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.
    });
}

Web namespaced API

// 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 Dynamic Links เพื่อส่งลิงก์อีเมลไปยังอุปกรณ์เคลื่อนที่ สำหรับการลงชื่อเข้าใช้ให้เสร็จสมบูรณ์ผ่านแอปพลิเคชันมือถือ แอปพลิเคชันจะต้องได้รับการกำหนดค่าให้ตรวจหาลิงก์แอปพลิเคชันที่เข้ามา แยกวิเคราะห์ลิงก์ในรายละเอียด และจากนั้นลงชื่อเข้าใช้ให้เสร็จสมบูรณ์ตามที่ทำผ่านเว็บโฟลว์

หากต้องการเรียนรู้เพิ่มเติมเกี่ยวกับวิธีจัดการกับการลงชื่อเข้าใช้ด้วยลิงก์อีเมลในแอปพลิเคชัน Android โปรดดู คู่มือ Android

หากต้องการเรียนรู้เพิ่มเติมเกี่ยวกับวิธีจัดการกับการลงชื่อเข้าใช้ด้วยลิงก์อีเมลในแอปพลิเคชันของ Apple โปรดดูที่ คู่มือแพลตฟอร์มของ Apple

คุณยังสามารถเชื่อมโยงวิธีการรับรองความถูกต้องนี้กับผู้ใช้ที่มีอยู่ ตัวอย่างเช่น ผู้ใช้ที่เคยตรวจสอบสิทธิ์กับผู้ให้บริการรายอื่น เช่น หมายเลขโทรศัพท์ สามารถเพิ่มวิธีการลงชื่อเข้าใช้นี้ในบัญชีที่มีอยู่ได้

ความแตกต่างจะอยู่ในช่วงครึ่งหลังของการดำเนินการ:

Web modular API

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 namespaced API

// 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 modular API

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 namespaced API

// 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.
  });

อย่างไรก็ตาม เนื่องจากโฟลว์อาจจบลงบนอุปกรณ์อื่นที่ผู้ใช้เดิมไม่ได้เข้าสู่ระบบ โฟลว์นี้จึงอาจไม่เสร็จสมบูรณ์ ในกรณีดังกล่าว ผู้ใช้อาจแสดงข้อผิดพลาดเพื่อบังคับให้เปิดลิงก์บนอุปกรณ์เดียวกัน สามารถส่งผ่านบางสถานะในลิงค์เพื่อให้ข้อมูลเกี่ยวกับประเภทของการดำเนินการและ uid ผู้ใช้

ในกรณีที่คุณรองรับทั้งรหัสผ่านและการลงชื่อเข้าใช้ด้วยลิงก์ด้วยอีเมล หากต้องการแยกวิธีการลงชื่อเข้าใช้สำหรับผู้ใช้รหัสผ่าน/ลิงก์ ให้ใช้ fetchSignInMethodsForEmail ซึ่งมีประโยชน์สำหรับโฟลว์ที่ใช้ตัวระบุเป็นอันดับแรก ซึ่งผู้ใช้จะถูกขอให้ระบุอีเมลก่อน จากนั้นจึงนำเสนอวิธีการลงชื่อเข้าใช้:

Web modular API

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

// After asking the user for their email.
const email = window.prompt('Please provide your email');

const auth = getAuth();
fetchSignInMethodsForEmail(auth, email)
  .then((signInMethods) => {
    // This returns the same array as fetchProvidersForEmail but for email
    // provider identified by 'password' string, signInMethods would contain 2
    // different strings:
    // 'emailLink' if the user previously signed in with an email/link
    // 'password' if the user has a password.
    // A user could have both.
    if (signInMethods.indexOf(EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD) != -1) {
      // User can sign in with email/password.
    }
    if (signInMethods.indexOf(EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD) != -1) {
      // User can sign in with email/link.
    }
  })
  .catch((error) => {
    // Some error occurred, you can inspect the code: error.code
  });

Web namespaced API

// After asking the user for their email.
var email = window.prompt('Please provide your email');
firebase.auth().fetchSignInMethodsForEmail(email)
  .then((signInMethods) => {
    // This returns the same array as fetchProvidersForEmail but for email
    // provider identified by 'password' string, signInMethods would contain 2
    // different strings:
    // 'emailLink' if the user previously signed in with an email/link
    // 'password' if the user has a password.
    // A user could have both.
    if (signInMethods.indexOf(
            firebase.auth.EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD) != -1) {
      // User can sign in with email/password.
    }
    if (signInMethods.indexOf(
            firebase.auth.EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD) != -1) {
      // User can sign in with email/link.
    }
  })
  .catch((error) => {
    // Some error occurred, you can inspect the code: error.code
  });

ตามที่อธิบายไว้ข้างต้น อีเมล/รหัสผ่าน และอีเมล/ลิงก์ ถือเป็น firebase.auth.EmailAuthProvider เดียวกัน ( PROVIDER_ID เดียวกัน) โดยมีวิธีการลงชื่อเข้าใช้ต่างกัน

ขั้นตอนถัดไป

หลังจากที่ผู้ใช้ลงชื่อเข้าใช้เป็นครั้งแรก บัญชีผู้ใช้ใหม่จะถูกสร้างขึ้นและเชื่อมโยงกับข้อมูลประจำตัว ซึ่งก็คือชื่อผู้ใช้และรหัสผ่าน หมายเลขโทรศัพท์ หรือข้อมูลผู้ให้บริการตรวจสอบสิทธิ์ ซึ่งผู้ใช้ลงชื่อเข้าใช้ด้วย บัญชีใหม่นี้จัดเก็บเป็นส่วนหนึ่งของโปรเจ็กต์ Firebase และสามารถใช้ระบุผู้ใช้ในทุกแอปในโครงการ ไม่ว่าผู้ใช้จะลงชื่อเข้าใช้ด้วยวิธีใดก็ตาม

  • ในแอปของคุณ วิธีที่แนะนำให้ทราบสถานะการตรวจสอบสิทธิ์ของผู้ใช้คือการตั้งค่าผู้สังเกตการณ์บนวัตถุ Auth จากนั้น คุณจะได้รับข้อมูลโปรไฟล์พื้นฐานของผู้ใช้จากวัตถุ User ดู จัดการผู้ใช้

  • ใน กฎความปลอดภัย ของ Firebase Realtime Database และ Cloud Storage คุณสามารถรับ ID ผู้ใช้ที่ไม่ซ้ำกันของผู้ใช้ที่ลงชื่อเข้าใช้จากตัวแปร auth และใช้เพื่อควบคุมข้อมูลที่ผู้ใช้สามารถเข้าถึงได้

คุณสามารถอนุญาตให้ผู้ใช้ลงชื่อเข้าใช้แอปของคุณโดยใช้ผู้ให้บริการตรวจสอบสิทธิ์หลายรายโดย เชื่อมโยงข้อมูลประจำตัวของผู้ให้บริการตรวจสอบสิทธิ์กับบัญชีผู้ใช้ที่มีอยู่

ในการออกจากระบบผู้ใช้ โทร signOut :

Web modular API

import { getAuth, signOut } from "firebase/auth";

const auth = getAuth();
signOut(auth).then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});

Web namespaced API

firebase.auth().signOut().then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});