Xác thực bằng Firebase trong một tiện ích của Chrome

Tài liệu này cho bạn biết cách sử dụng tính năng Xác thực Firebase để đăng nhập người dùng vào một tiện ích của Chrome sử dụng Manifest V3.

Tính năng Xác thực Firebase cung cấp nhiều phương thức xác thực để đăng nhập người dùng từ một tiện ích của Chrome, một số phương thức đòi hỏi nhiều nỗ lực phát triển hơn so với những phương thức khác.

Để sử dụng các phương thức sau trong tiện ích Manifest V3 của Chrome, bạn chỉ cần nhập các phương thức đó từ firebase/auth/web-extension:

  • Đăng nhập bằng email và mật khẩu (createUserWithEmailAndPasswordsignInWithEmailAndPassword)
  • Đăng nhập bằng đường liên kết đến email (sendSignInLinkToEmail, isSignInWithEmailLinksignInWithEmailLink)
  • Đăng nhập ẩn danh (signInAnonymously)
  • Đăng nhập bằng hệ thống xác thực tuỳ chỉnh (signInWithCustomToken)
  • Xử lý hoạt động đăng nhập độc lập của nhà cung cấp sau đó sử dụng signInWithCredential

Các phương thức đăng nhập sau đây cũng được hỗ trợ nhưng yêu cầu thêm một số thao tác:

  • Đăng nhập bằng cửa sổ bật lên (signInWithPopup, linkWithPopupreauthenticateWithPopup)
  • Đăng nhập bằng cách chuyển hướng đến trang đăng nhập (signInWithRedirect, linkWithRedirectreauthenticateWithRedirect)
  • Đăng nhập bằng số điện thoại bằng reCAPTCHA
  • Xác thực đa yếu tố qua SMS bằng reCAPTCHA
  • Biện pháp bảo vệ cho reCAPTCHA Enterprise

Để sử dụng các phương thức này trong tiện ích Manifest V3 của Chrome, bạn phải sử dụng Tài liệu ngoài màn hình.

Sử dụng điểm truy cập firebase/auth/web-extension

Việc nhập từ firebase/auth/web-extension sẽ giúp người dùng đăng nhập từ tiện ích của Chrome tương tự như ứng dụng web.

firebase/auth/web-extension chỉ được hỗ trợ trên phiên bản SDK web v10.8.0 trở lên.

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

Sử dụng tài liệu ngoài màn hình

Một số phương thức xác thực, chẳng hạn như signInWithPopup, linkWithPopupreauthenticateWithPopup, không tương thích trực tiếp với các tiện ích của Chrome, vì các phương thức này yêu cầu tải mã từ bên ngoài gói tiện ích. Kể từ Manifest V3, tính năng này không được phép và sẽ bị nền tảng tiện ích chặn. Để khắc phục vấn đề này, bạn có thể tải mã đó trong một iframe bằng cách sử dụng một tài liệu ngoài màn hình. Trong tài liệu ngoài màn hình, hãy triển khai quy trình xác thực thông thường và chuyển kết quả từ tài liệu ngoài màn hình trở lại tiện ích.

Hướng dẫn này dùng signInWithPopup làm ví dụ, nhưng khái niệm tương tự cũng áp dụng cho các phương thức xác thực khác.

Trước khi bắt đầu

Kỹ thuật này yêu cầu bạn thiết lập trang web có thể truy cập được trên web mà bạn sẽ tải trong iframe. Mọi máy chủ lưu trữ đều làm việc này, kể cả dịch vụ Lưu trữ Firebase. Tạo một trang web có nội dung sau:

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

Đăng nhập liên kết

Nếu đang sử dụng tính năng đăng nhập liên kết, chẳng hạn như đăng nhập bằng Google, Apple, SAML hoặc OIDC, bạn phải thêm mã tiện ích của Chrome vào danh sách miền được uỷ quyền:

  1. Mở dự án của bạn trong bảng điều khiển của Firebase.
  2. Trong phần Xác thực, mở trang Cài đặt.
  3. Thêm một URI như sau vào danh sách Miền được uỷ quyền:
    chrome-extension://CHROME_EXTENSION_ID

Trong tệp kê khai của tiện ích Chrome, hãy đảm bảo rằng bạn thêm các URL sau vào danh sách cho phép content_security_policy:

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

Triển khai phương thức xác thực

Trong tài liệu HTML, signInWithPopup.js là mã JavaScript xử lý quá trình xác thực. Có 2 cách để triển khai một phương thức được hỗ trợ trực tiếp trong tiện ích:

  • Sử dụng firebase/auth thay vì firebase/auth/web-extension. Điểm truy cập web-extension dành cho mã chạy trong tiện ích. Mặc dù mã này cuối cùng sẽ chạy trong tiện ích (trong iframe, trong tài liệu ngoài màn hình của bạn), nhưng ngữ cảnh mà mã đang chạy là trên web chuẩn.
  • Gói logic xác thực trong trình nghe postMessage để proxy yêu cầu và phản hồi xác thực.
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)
  }
});

Tạo tiện ích của Chrome

Sau khi trang web đi vào hoạt động, bạn có thể sử dụng trang web trong Tiện ích của Chrome.

  1. Thêm quyền offscreen vào tệp manifest.json:
  2.     {
          "name": "signInWithPopup Demo",
          "manifest_version" 3,
          "background": {
            "service_worker": "background.js"
          },
          "permissions": [
            "offscreen"
          ]
        }
        
  3. Tự tạo tài liệu ngoài màn hình. Đây là tệp HTML tối thiểu bên trong gói tiện ích, có chức năng tải logic của JavaScript tài liệu ngoài màn hình:
  4.     <!DOCTYPE html>
        <script src="./offscreen.js"></script>
        
  5. Thêm offscreen.js vào gói tiện ích của bạn. URL này đóng vai trò là proxy giữa trang web công khai mà bạn đã thiết lập ở bước 1 và tiện ích của bạn.
  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. Thiết lập tài liệu ngoài màn hình từ trình chạy dịch vụ 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;
        }
        

    Giờ đây, khi bạn gọi firebaseAuth() trong trình chạy dịch vụ, trình chạy dịch vụ này sẽ tạo tài liệu ngoài màn hình và tải trang web vào iframe. iframe đó sẽ xử lý ở chế độ nền và Firebase sẽ trải qua quy trình xác thực tiêu chuẩn. Sau khi giải quyết hoặc bị từ chối, đối tượng xác thực sẽ được proxy từ iframe của bạn tới trình chạy dịch vụ, bằng cách sử dụng tài liệu ngoài màn hình.