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

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

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

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

ก่อนเริ่มต้น

หากยังไม่ได้ทำ ให้คัดลอกข้อมูลโค้ดเริ่มต้นจากFirebaseคอนโซลไปยังโปรเจ็กต์ตามที่อธิบายไว้ใน เพิ่ม Firebase ลงในโปรเจ็กต์ JavaScript

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

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

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

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

    • url: Deep Link ที่จะฝังและสถานะเพิ่มเติมที่จะส่งต่อ คุณต้องเพิ่มโดเมนของลิงก์ในรายการโดเมนที่ได้รับอนุญาตของคอนโซล Firebase ซึ่งดูได้โดยไปที่แท็บวิธีการลงชื่อเข้าใช้ (การตรวจสอบสิทธิ์ -> การตั้งค่า)
    • android และ ios: ช่วยให้ Firebase Authentication ตัดสินใจได้ว่าควรสร้างลิงก์สำหรับเว็บเท่านั้นหรือลิงก์สำหรับอุปกรณ์เคลื่อนที่ซึ่งเปิดในอุปกรณ์ Android หรือ Apple
    • handleCodeInApp: ตั้งค่าเป็น "จริง" การดำเนินการลงชื่อเข้าใช้ต้องดำเนินการให้เสร็จสมบูรณ์ในแอปเสมอ ซึ่งแตกต่างจากการดำเนินการอื่นๆ ทางอีเมลนอกแบนด์ (การรีเซ็ตรหัสผ่านและการยืนยันอีเมล) เนื่องจากเมื่อสิ้นสุดขั้นตอน ผู้ใช้จะลงชื่อเข้าใช้และสถานะการตรวจสอบสิทธิ์จะยังคงอยู่ในแอป
    • 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'
        },
        dynamicLinkDomain: 'example.page.link'
      };

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

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

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

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

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

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

ดูข้อมูลเพิ่มเติมเกี่ยวกับวิธีจัดการการลงชื่อเข้าใช้ด้วยลิงก์อีเมลในแอปพลิเคชัน 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.
  });

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

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

แม้ว่าคุณจะปิดใช้การป้องกันการระบุอีเมลสำหรับโปรเจ็กต์ได้ แต่เราไม่แนะนำให้ทำเช่นนั้น

ดูรายละเอียดเพิ่มเติมในเอกสารประกอบเกี่ยวกับการป้องกันการระบุอีเมล

เทมเพลตอีเมลเริ่มต้นสำหรับการลงชื่อเข้าใช้ด้วยลิงก์

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

เทมเพลตนี้ใช้ได้กับภาษาต่อไปนี้

รหัส ภาษา
อาหรับ อาหรับ
zh-CN จีน (ตัวย่อ)
zh-TW จีน (ดั้งเดิม)
nl ดัตช์
en อังกฤษ
en-GB อังกฤษ (สหราชอาณาจักร)
fr ฝรั่งเศส
de เยอรมัน
id อินโดนีเซีย
it อิตาลี
ja ญี่ปุ่น
เกาหลี เกาหลี
โปแลนด์ โปแลนด์
pt-BR โปรตุเกส (บราซิล)
โปรตุเกส (โปรตุเกส) โปรตุเกส (โปรตุเกส)
รัสเซีย รัสเซีย
สเปน สเปน
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.
});