ตรวจสอบสิทธิ์ด้วย Firebase ในส่วนขยายของ Chrome

เอกสารนี้แสดงวิธีใช้ Firebase Authentication เพื่อลงชื่อเข้าใช้ผู้ใช้ในส่วนขยาย Chrome ที่ใช้ Manifest V3

การตรวจสอบสิทธิ์ Firebase มีวิธีการตรวจสอบสิทธิ์หลายวิธีในการลงชื่อเข้าใช้ผู้ใช้จากส่วนขยาย Chrome ซึ่งบางวิธีต้องใช้ความพยายามในการพัฒนามากกว่าวิธีอื่นๆ

หากต้องการใช้วิธีการต่อไปนี้ในส่วนขยาย Chrome Manifest V3 คุณจะต้อง นำเข้าจาก firebase/auth/web-extension เท่านั้น :

  • ลงชื่อเข้าใช้ด้วยอีเมลและรหัสผ่าน ( createUserWithEmailAndPassword และ signInWithEmailAndPassword )
  • ลงชื่อเข้าใช้ด้วยลิงก์อีเมล ( sendSignInLinkToEmail , isSignInWithEmailLink และ signInWithEmailLink )
  • ลงชื่อเข้าใช้โดยไม่ระบุชื่อ ( signInAnonymously )
  • ลงชื่อเข้าใช้ด้วยระบบการตรวจสอบสิทธิ์ที่กำหนดเอง ( signInWithCustomToken )
  • จัดการการลงชื่อเข้าใช้ของผู้ให้บริการอย่างอิสระ จากนั้นใช้ signInWithCredential

วิธีการลงชื่อเข้าใช้ต่อไปนี้ยังได้รับการสนับสนุน แต่ต้องมีการทำงานเพิ่มเติมบางอย่าง:

  • ลงชื่อเข้าใช้ด้วยหน้าต่างป๊อปอัป ( signInWithPopup , linkWithPopup และ reauthenticateWithPopup )
  • ลงชื่อเข้าใช้โดยการเปลี่ยนเส้นทางไปยังหน้าลงชื่อเข้าใช้ ( signInWithRedirect , linkWithRedirect และ reauthenticateWithRedirect )
  • ลงชื่อเข้าใช้ด้วยหมายเลขโทรศัพท์ด้วย reCAPTCHA
  • การรับรองความถูกต้องด้วย SMS หลายปัจจัยพร้อม reCAPTCHA
  • การป้องกันองค์กร reCAPTCHA

หากต้องการใช้วิธีการเหล่านี้ในส่วนขยาย Chrome อย่าง Manifest V3 คุณต้องใช้ Offscreen Documents

ใช้จุดเริ่มต้น firebase/auth/web-extension

การนำเข้าจาก firebase/auth/web-extension ทำให้ผู้ใช้ลงชื่อเข้าใช้จากส่วนขยาย Chrome คล้ายกับเว็บแอป

firebase/auth/web-extension รองรับ Web SDK เวอร์ชัน v10.8.0 ขึ้นไปเท่านั้น

import { getAuth, signInWithEmailAndPassword } from 'firebase/auth/web-extension';

const auth = getAuth();
signInWithEmailAndPassword(auth, email, password)
  .then((userCredential) => {
    // Signed in
    const user = userCredential.user;
    // ...
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
  });

ใช้เอกสารนอกจอ

วิธีการตรวจสอบสิทธิ์บางวิธี เช่น signInWithPopup , linkWithPopup และ reauthenticateWithPopup ไม่สามารถทำงานร่วมกับส่วนขยาย Chrome ได้โดยตรง เนื่องจากต้องใช้รหัสในการโหลดจากภายนอกแพ็คเกจส่วนขยาย ตั้งแต่ใน Manifest V3 เป็นต้นไป จะไม่ได้รับอนุญาตและจะถูกบล็อกโดยแพลตฟอร์มส่วนขยาย เพื่อแก้ไขปัญหานี้ คุณสามารถโหลดโค้ดนั้นภายใน iframe โดยใช้ เอกสารนอกหน้าจอ ในเอกสารนอกหน้าจอ ให้ใช้ขั้นตอนการตรวจสอบสิทธิ์ตามปกติและพร็อกซีผลลัพธ์จากเอกสารนอกหน้าจอกลับไปยังส่วนขยาย

คู่มือนี้ใช้ signInWithPopup เป็นตัวอย่าง แต่แนวคิดเดียวกันนี้ใช้กับวิธีการรับรองความถูกต้องอื่นๆ

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

เทคนิคนี้กำหนดให้คุณต้องตั้งค่าหน้าเว็บที่มีอยู่บนเว็บ และคุณจะโหลดใน iframe โฮสต์ใดก็ได้ที่ใช้งานได้ รวมถึง Firebase Hosting ด้วย สร้างเว็บไซต์ที่มีเนื้อหาดังต่อไปนี้:

<!DOCTYPE html>
<html>
  <head>
    <title>signInWithPopup</title>
    <script src="signInWithPopup.js"></script>
  </head>
  <body><h1>signInWithPopup</h1></body>
</html>

ลงชื่อเข้าใช้แบบรวมศูนย์

หากคุณใช้การลงชื่อเข้าใช้แบบรวมศูนย์ เช่น ลงชื่อเข้าใช้ด้วย Google, Apple, SAML หรือ OIDC คุณต้องเพิ่ม ID ส่วนขยาย Chrome ของคุณลงในรายการโดเมนที่ได้รับอนุญาต:

  1. เปิดโครงการของคุณใน คอนโซล Firebase
  2. ในส่วน การรับรองความถูกต้อง ให้เปิดหน้า การตั้งค่า
  3. เพิ่ม URI ดังต่อไปนี้ลงในรายการโดเมนที่ได้รับอนุญาต:
    chrome-extension://CHROME_EXTENSION_ID

ในไฟล์ Manifest ของส่วนขยาย Chrome ตรวจสอบให้แน่ใจว่าคุณเพิ่ม URL ต่อไปนี้ในรายการที่อนุญาต content_security_policy :

  • https://apis.google.com
  • https://www.gstatic.com
  • https://www.googleapis.com
  • https://securetoken.googleapis.com

ดำเนินการรับรองความถูกต้อง

ในเอกสาร HTML ของคุณ signInWithPopup.js คือโค้ด JavaScript ที่จัดการการตรวจสอบสิทธิ์ มีสองวิธีที่แตกต่างกันในการใช้วิธีที่ได้รับการสนับสนุนโดยตรงในส่วนขยาย:

  • ใช้ firebase/auth แทน firebase/auth/web-extension จุดเข้าใช้งาน web-extension ใช้สำหรับโค้ดที่ทำงานภายในส่วนขยาย แม้ว่าโค้ดนี้จะทำงานในส่วนขยายในที่สุด (ใน iframe ในเอกสารนอกหน้าจอของคุณ) แต่บริบทที่โค้ดกำลังทำงานอยู่ก็คือเว็บมาตรฐาน
  • รวมตรรกะการรับรองความถูกต้องไว้ในฟัง postMessage เพื่อพร็อกซีคำขอการรับรองความถูกต้องและการตอบกลับ
import { signInWithPopup, GoogleAuthProvider, getAuth } from'firebase/auth';
import { initializeApp } from 'firebase/app';
import firebaseConfig from './firebaseConfig.js'

const app = initializeApp(firebaseConfig);
const auth = getAuth();

// This code runs inside of an iframe in the extension's offscreen document.
// This gives you a reference to the parent frame, i.e. the offscreen document.
// You will need this to assign the targetOrigin for postMessage.
const PARENT_FRAME = document.location.ancestorOrigins[0];

// This demo uses the Google auth provider, but any supported provider works.
// Make sure that you enable any provider you want to use in the Firebase Console.
// https://console.firebase.google.com/project/_/authentication/providers
const PROVIDER = new GoogleAuthProvider();

function sendResponse(result) {
  globalThis.parent.self.postMessage(JSON.stringify(result), PARENT_FRAME);
}

globalThis.addEventListener('message', function({data}) {
  if (data.initAuth) {
    // Opens the Google sign-in page in a popup, inside of an iframe in the
    // extension's offscreen document.
    // To centralize logic, all respones are forwarded to the parent frame,
    // which goes on to forward them to the extension's service worker.
    signInWithPopup(auth, PROVIDER)
      .then(sendResponse)
      .catch(sendResponse)
  }
});

สร้างส่วนขยาย Chrome ของคุณ

หลังจากที่เว็บไซต์ของคุณเผยแพร่แล้ว คุณสามารถใช้เว็บไซต์ดังกล่าวในส่วนขยาย Chrome ได้

  1. เพิ่มการอนุญาต offscreen ให้กับไฟล์ manifest.json ของคุณ:
  2.     {
          "name": "signInWithPopup Demo",
          "manifest_version" 3,
          "background": {
            "service_worker": "background.js"
          },
          "permissions": [
            "offscreen"
          ]
        }
        
  3. สร้างเอกสารนอกหน้าจอเอง นี่คือไฟล์ HTML ขั้นต่ำภายในแพ็คเกจส่วนขยายของคุณที่โหลดตรรกะของ JavaScript เอกสารนอกหน้าจอของคุณ:
  4.     <!DOCTYPE html>
        <script src="./offscreen.js"></script>
        
  5. รวม offscreen.js ไว้ในแพ็คเกจส่วนขยายของคุณ โดยทำหน้าที่เป็นพร็อกซีระหว่างเว็บไซต์สาธารณะที่ตั้งค่าในขั้นตอนที่ 1 และส่วนขยายของคุณ
  6.     // This URL must point to the public site
        const _URL = 'https://example.com/signInWithPopupExample';
        const iframe = document.createElement('iframe');
        iframe.src = _URL;
        document.documentElement.appendChild(iframe);
        chrome.runtime.onMessage.addListener(handleChromeMessages);
    
        function handleChromeMessages(message, sender, sendResponse) {
          // Extensions may have an number of other reasons to send messages, so you
          // should filter out any that are not meant for the offscreen document.
          if (message.target !== 'offscreen') {
            return false;
          }
    
          function handleIframeMessage({data}) {
            try {
              if (data.startsWith('!_{')) {
                // Other parts of the Firebase library send messages using postMessage.
                // You don't care about them in this context, so return early.
                return;
              }
              data = JSON.parse(data);
              self.removeEventListener('message', handleIframeMessage);
    
              sendResponse(data);
            } catch (e) {
              console.log(`json parse failed - ${e.message}`);
            }
          }
    
          globalThis.addEventListener('message', handleIframeMessage, false);
    
          // Initialize the authentication flow in the iframed document. You must set the
          // second argument (targetOrigin) of the message in order for it to be successfully
          // delivered.
          iframe.contentWindow.postMessage({"initAuth": true}, new URL(_URL).origin);
          return true;
        }
        
  7. ตั้งค่าเอกสารนอกหน้าจอจากพนักงานบริการของ background.js
  8.     const OFFSCREEN_DOCUMENT_PATH = '/offscreen.html';
    
        // A global promise to avoid concurrency issues
        let creatingOffscreenDocument;
    
        // Chrome only allows for a single offscreenDocument. This is a helper function
        // that returns a boolean indicating if a document is already active.
        async function hasDocument() {
          // Check all windows controlled by the service worker to see if one
          // of them is the offscreen document with the given path
          const matchedClients = await clients.matchAll();
          return matchedClients.some(
            (c) => c.url === chrome.runtime.getURL(OFFSCREEN_DOCUMENT_PATH)
          );
        }
    
        async function setupOffscreenDocument(path) {
          // If we do not have a document, we are already setup and can skip
          if (!(await hasDocument())) {
            // create offscreen document
            if (creating) {
              await creating;
            } else {
              creating = chrome.offscreen.createDocument({
                url: path,
                reasons: [
                    chrome.offscreen.Reason.DOM_SCRAPING
                ],
                justification: 'authentication'
              });
              await creating;
              creating = null;
            }
          }
        }
    
        async function closeOffscreenDocument() {
          if (!(await hasDocument())) {
            return;
          }
          await chrome.offscreen.closeDocument();
        }
    
        function getAuth() {
          return new Promise(async (resolve, reject) => {
            const auth = await chrome.runtime.sendMessage({
              type: 'firebase-auth',
              target: 'offscreen'
            });
            auth?.name !== 'FirebaseError' ? resolve(auth) : reject(auth);
          })
        }
    
        async function firebaseAuth() {
          await setupOffscreenDocument(OFFSCREEN_DOCUMENT_PATH);
    
          const auth = await getAuth()
            .then((auth) => {
              console.log('User Authenticated', auth);
              return auth;
            })
            .catch(err => {
              if (err.code === 'auth/operation-not-allowed') {
                console.error('You must enable an OAuth provider in the Firebase' +
                              ' console in order to use signInWithPopup. This sample' +
                              ' uses Google by default.');
              } else {
                console.error(err);
                return err;
              }
            })
            .finally(closeOffscreenDocument)
    
          return auth;
        }
        

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