Uwierzytelnij się w Firebase w rozszerzeniu Chrome

W tym dokumencie pokazano, jak używać uwierzytelniania Firebase do logowania użytkowników w rozszerzeniu Chrome korzystającym z Manifest V3 .

Uwierzytelnianie Firebase zapewnia wiele metod uwierzytelniania umożliwiających logowanie użytkowników z rozszerzenia Chrome, niektóre wymagają więcej wysiłku programistycznego niż inne.

Aby użyć następujących metod w rozszerzeniu Manifest V3 dla Chrome, wystarczy zaimportować je z firebase/auth/web-extension :

  • Zaloguj się za pomocą adresu e-mail i hasła ( createUserWithEmailAndPassword signInWithEmailAndPassword )
  • Zaloguj się za pomocą łącza e-mail ( sendSignInLinkToEmail , isSignInWithEmailLink signInWithEmailLink )
  • Zaloguj się anonimowo ( signInAnonymously )
  • Zaloguj się za pomocą niestandardowego systemu uwierzytelniania ( signInWithCustomToken )
  • Obsługuj logowanie dostawcy niezależnie, a następnie użyj signInWithCredential

Obsługiwane są również następujące metody logowania, ale wymagają dodatkowej pracy:

  • Zaloguj się za pomocą wyskakującego okna ( signInWithPopup , linkWithPopup i reauthenticateWithPopup )
  • Zaloguj się, przekierowując do strony logowania ( signInWithRedirect , linkWithRedirect i reauthenticateWithRedirect )
  • Zaloguj się przy użyciu numeru telefonu za pomocą reCAPTCHA
  • Wielopoziomowe uwierzytelnianie SMS za pomocą reCAPTCHA
  • reCAPTCHA Ochrona przedsiębiorstwa

Aby użyć tych metod w rozszerzeniu Manifest V3 do przeglądarki Chrome, musisz użyć Dokumentów pozaekranowych .

Użyj punktu wejścia firebase/auth/web-extension

Importowanie z firebase/auth/web-extension sprawia, że ​​logowanie użytkowników z rozszerzenia do Chrome jest podobne do aplikacji internetowej.

rozszerzenie firebase/auth/web-extension jest obsługiwane tylko w wersjach Web SDK v10.8.0 i nowszych.

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

Użyj dokumentów poza ekranem

Niektóre metody uwierzytelniania, takie signInWithPopup , linkWithPopup i reauthenticateWithPopup , nie są bezpośrednio kompatybilne z rozszerzeniami przeglądarki Chrome, ponieważ wymagają załadowania kodu spoza pakietu rozszerzeń. Począwszy od Manifest V3, jest to niedozwolone i będzie blokowane przez platformę rozszerzeń. Aby obejść ten problem, możesz załadować ten kod w ramce iframe, korzystając z dokumentu znajdującego się poza ekranem . W dokumencie poza ekranem zaimplementuj normalny przepływ uwierzytelniania i przekaż wynik z dokumentu poza ekranem z powrotem do rozszerzenia.

W tym przewodniku jako przykład wykorzystano signInWithPopup , ale ta sama koncepcja dotyczy innych metod uwierzytelniania.

Zanim zaczniesz

Ta technika wymaga skonfigurowania strony internetowej dostępnej w Internecie, którą załadujesz w ramce iframe. Działa w tym przypadku każdy host, w tym Hosting Firebase . Utwórz witrynę internetową o następującej treści:

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

Logowanie federacyjne

Jeśli korzystasz z logowania federacyjnego, np. za pomocą Google, Apple, SAML lub OIDC, musisz dodać identyfikator rozszerzenia Chrome do listy autoryzowanych domen:

  1. Otwórz swój projekt w konsoli Firebase .
  2. W sekcji Uwierzytelnianie otwórz stronę Ustawienia .
  3. Dodaj identyfikator URI podobny do poniższego do listy autoryzowanych domen:
    chrome-extension://CHROME_EXTENSION_ID

W pliku manifestu rozszerzenia do Chrome upewnij się, że do listy dozwolonych content_security_policy dodano następujące adresy URL:

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

Zaimplementuj uwierzytelnianie

W dokumencie HTML znak SignInWithPopup.js to kod JavaScript obsługujący uwierzytelnianie. Istnieją dwa różne sposoby implementacji metody, która jest bezpośrednio obsługiwana w rozszerzeniu:

  • Użyj firebase/auth zamiast firebase/auth/web-extension . Punkt wejścia web-extension jest przeznaczony dla kodu działającego w rozszerzeniu. Chociaż ten kod ostatecznie działa w rozszerzeniu (w ramce iframe, w dokumencie poza ekranem), kontekst, w którym działa, to standardowy plik web.
  • Zawiń logikę uwierzytelniania w odbiorniku postMessage , aby przekazać żądanie uwierzytelnienia i odpowiedź.
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)
  }
});

Utwórz rozszerzenie do przeglądarki Chrome

Po uruchomieniu witryny możesz używać jej w rozszerzeniu Chrome.

  1. Dodaj uprawnienia offscreen do pliku manifest.json:
  2.     {
          "name": "signInWithPopup Demo",
          "manifest_version" 3,
          "background": {
            "service_worker": "background.js"
          },
          "permissions": [
            "offscreen"
          ]
        }
        
  3. Utwórz sam dokument poza ekranem. Jest to minimalny plik HTML znajdujący się w pakiecie rozszerzeń, który ładuje logikę JavaScript dokumentu znajdującego się poza ekranem:
  4.     <!DOCTYPE html>
        <script src="./offscreen.js"></script>
        
  5. Dołącz offscreen.js do swojego pakietu rozszerzeń. Działa jako serwer proxy pomiędzy publiczną witryną internetową skonfigurowaną w kroku 1 a Twoim rozszerzeniem.
  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. Skonfiguruj dokument poza ekranem z poziomu pracownika usługi w tle.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;
        }
        

    Teraz, gdy wywołasz funkcję firebaseAuth() w swoim pracowniku usługi, utworzy on dokument poza ekranem i załaduje witrynę w ramce iframe. Ta ramka iframe będzie przetwarzana w tle, a Firebase przejdzie standardowy proces uwierzytelniania. Po rozwiązaniu lub odrzuceniu obiekt uwierzytelniający zostanie przesłany z ramki iframe do pracownika usługi przy użyciu dokumentu znajdującego się poza ekranem.