本文檔向您展示如何使用 Firebase 驗證將使用者登入使用Manifest V3 的Chrome 擴充功能。
Firebase 驗證提供了多種身份驗證方法來從 Chrome 擴充功能登入用戶,其中一些方法比其他方法需要更多的開發工作。
要在 Manifest V3 Chrome 擴充功能中使用以下方法,您只需從firebase/auth/web-extension
匯入它們:
- 使用電子郵件和密碼登入(
createUserWithEmailAndPassword
和signInWithEmailAndPassword
) - 使用電子郵件連結登入(
sendSignInLinkToEmail
、isSignInWithEmailLink
和signInWithEmailLink
) - 匿名登入 (
signInAnonymously
) - 使用自訂身份驗證系統登入 (
signInWithCustomToken
) - 獨立處理提供者登錄,然後使用
signInWithCredential
也支援以下登入方法,但需要一些額外的工作:
- 使用彈出視窗登入(
signInWithPopup
、linkWithPopup
和reauthenticateWithPopup
) - 透過重新導向至登入頁面(
signInWithRedirect
、linkWithRedirect
和reauthenticateWithRedirect
)進行登入 - 使用 reCAPTCHA 的電話號碼登錄
- 使用 reCAPTCHA 進行 SMS 多重身份驗證
- reCAPTCHA 企業保護
要在 Manifest V3 Chrome 擴充功能中使用這些方法,您必須使用Offscreen Documents 。
使用 firebase/auth/web-extension 入口點
從firebase/auth/web-extension
導入讓使用者可以從類似 Web 應用程式的 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 登錄,則必須將您的 Chrome 擴充功能 ID 新增至授權網域清單:
- 在Firebase 控制台中開啟您的專案。
- 在「身份驗證」部分中,開啟「設定」頁面。
- 將如下所示的 URI 加入到授權網域清單中:
chrome-extension://CHROME_EXTENSION_ID
在 Chrome 擴充功能的清單檔案中,確保將以下網址新增至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 中,在螢幕外文檔中),但它運行的上下文是標準 Web。 - 將身份驗證邏輯包裝在
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 擴充功能中使用它。
- 將
offscreen
權限加入您的manifest.json 檔案: - 建立離屏文檔本身。這是擴充包內的一個最小 HTML 文件,用於載入螢幕外文檔 JavaScript 的邏輯:
- 將
offscreen.js
包含在您的擴充包中。它充當步驟 1 中設定的公共網站和您的分機之間的代理。 - 從 background.js 服務工作人員設定螢幕外文件。
{ "name": "signInWithPopup Demo", "manifest_version" 3, "background": { "service_worker": "background.js" }, "permissions": [ "offscreen" ] }
<!DOCTYPE html> <script src="./offscreen.js"></script>
// 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; }
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; }
現在,當您在 Service Worker 中呼叫firebaseAuth()
時,它將建立螢幕外文件並將網站載入到 iframe 中。該 iframe 將在背景處理,Firebase 將完成標準身份驗證流程。一旦解決或拒絕,身份驗證物件將使用螢幕外文件從您的 iframe 代理程式到您的 Service Worker。