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

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

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

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

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

ก่อนจะเริ่ม

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

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

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

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

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

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

      Web version 9

      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 version 8

      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 ในส่วนการดำเนินการของอีเมล

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

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

    Web version 9

    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 version 8

    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 ในการผลิตเพื่อหลีกเลี่ยงไม่ให้ลิงก์ของคุณถูกสกัดกั้นโดยเซิร์ฟเวอร์ตัวกลาง

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

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

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

Web version 9

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 version 8

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

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

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

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

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

Web version 9

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 version 8

// 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 version 9

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 version 8

// 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 version 9

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 version 8

// 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 Security Rules คุณสามารถรับ ID ผู้ใช้เฉพาะของผู้ใช้ที่ลงชื่อเข้าใช้จากตัวแปร auth และใช้เพื่อควบคุมข้อมูลที่ผู้ใช้สามารถเข้าถึงได้

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

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

Web version 9

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

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

Web version 8

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