Chrome एक्सटेंशन में Firebase की मदद से पुष्टि करें

इस दस्तावेज़ में, मेनिफ़ेस्ट V3 का इस्तेमाल करने वाले Chrome एक्सटेंशन में उपयोगकर्ताओं को साइन इन करने के लिए, Firebase से पुष्टि करने की सुविधा का इस्तेमाल करने का तरीका बताया गया है.

Firebase से पुष्टि करने की सुविधा से, उपयोगकर्ताओं को Chrome एक्सटेंशन से साइन इन करने के लिए पुष्टि करने के कई तरीके मिलते हैं. इनमें से कुछ तरीकों को डेवलप करने के लिए ज़्यादा मेहनत की ज़रूरत होती है.

मेनिफ़ेस्ट V3 Chrome एक्सटेंशन में इन तरीकों का इस्तेमाल करने के लिए, आपको सिर्फ़ उन्हें firebase/auth/web-extension से इंपोर्ट करना होगा:

  • ईमेल और पासवर्ड (createUserWithEmailAndPassword और signInWithEmailAndPassword) से साइन इन करें
  • ईमेल लिंक (sendSignInLinkToEmail, isSignInWithEmailLink, और signInWithEmailLink) से साइन इन करें
  • पहचान छिपाकर साइन इन करें (signInAnonymously)
  • कस्टम पुष्टि करने वाले सिस्टम (signInWithCustomToken) से साइन इन करें
  • सेवा देने वाली कंपनी के साइन इन को अलग से मैनेज करें. इसके बाद, signInWithCredential का इस्तेमाल करें

साइन इन करने के ये तरीके भी काम करते हैं, लेकिन इनके लिए कुछ और काम करने की ज़रूरत होती है:

  • पॉप-अप विंडो (signInWithPopup, linkWithPopup, और reauthenticateWithPopup) का इस्तेमाल करके साइन इन करें
  • साइन इन पेज (signInWithRedirect, linkWithRedirect, और reauthenticateWithRedirect) पर रीडायरेक्ट करके साइन इन करें
  • reCAPTCHA की मदद से फ़ोन नंबर से साइन इन करें
  • reCAPTCHA की मदद से एसएमएस के ज़रिए बहु-स्तरीय पुष्टि (MFA) करें
  • reCAPTCHA Enterprise की सुरक्षा

मेनिफ़ेस्ट V3 Chrome एक्सटेंशन में इन तरीकों का इस्तेमाल करने के लिए, आपको ऑफ़स्क्रीन दस्तावेज़ का इस्तेमाल करना होगा.

Firebase/auth/वेब एक्सटेंशन के एंट्री पॉइंट का इस्तेमाल करें

firebase/auth/web-extension से इंपोर्ट करने पर, उपयोगकर्ता किसी वेब ऐप्लिकेशन से मिलते-जुलते Chrome एक्सटेंशन से भी साइन इन कर सकते हैं.

Firebase/auth/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 एक्सटेंशन के साथ काम नहीं करते हैं. ऐसा इसलिए होता है, क्योंकि इनमें एक्सटेंशन पैकेज के बाहर से कोड को लोड करना ज़रूरी होता है. मेनिफ़ेस्ट V3 से शुरू होने वाले वर्शन में, इसकी अनुमति नहीं है. साथ ही, इसे एक्सटेंशन प्लैटफ़ॉर्म से ब्लॉक कर दिया जाएगा. इससे बचने के लिए, आप उस कोड को ऑफ़स्क्रीन दस्तावेज़ का इस्तेमाल करके iframe में लोड कर सकते हैं. ऑफ़स्क्रीन दस्तावेज़ में, पुष्टि करने का सामान्य तरीका लागू करें और ऑफ़स्क्रीन दस्तावेज़ से नतीजे को वापस एक्सटेंशन पर प्रॉक्सी करें.

इस गाइड में उदाहरण के तौर पर, signInWithPopup का इस्तेमाल किया गया है. हालांकि, पुष्टि करने के अन्य तरीकों पर भी यही सिद्धांत लागू होता है.

वेब कंटेनर इंस्टॉल करने से पहले

इस तकनीक का इस्तेमाल करने के लिए, आपको ऐसा वेब पेज सेट अप करना होगा जो वेब पर उपलब्ध हो और उसे iframe में लोड करें. इसके लिए कोई भी होस्ट काम करता है, जिसमें Firebase होस्टिंग शामिल है. इस कॉन्टेंट वाली वेबसाइट बनाएं:

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

फ़ेडरेटेड साइन इन

अगर फ़ेडरेटेड साइन इन का इस्तेमाल किया जा रहा है, जैसे कि Google, Apple, एसएएमएल या OIDC से साइन इन करना, तो आपको अनुमति वाले डोमेन की सूची में अपना Chrome एक्सटेंशन आईडी जोड़ना होगा:

  1. Firebase कंसोल में अपना प्रोजेक्ट खोलें.
  2. पुष्टि करना सेक्शन में, सेटिंग पेज खोलें.
  3. अनुमति वाले डोमेन की सूची में, इस तरह का यूआरआई जोड़ें:
    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

प्रमाणीकरण लागू करें

आपके एचटीएमएल दस्तावेज़ में, signInWithPopup.js एक JavaScript कोड है. यह पुष्टि करने का काम करता है. एक्सटेंशन में सीधे तौर पर काम करने वाला तरीका लागू करने के दो अलग-अलग तरीके हैं:

  • firebase/auth/web-extension के बजाय firebase/auth का इस्तेमाल करें. 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. अपनी Manifest.json फ़ाइल में, offscreen की अनुमति जोड़ें:
  2.     {
          "name": "signInWithPopup Demo",
          "manifest_version" 3,
          "background": {
            "service_worker": "background.js"
          },
          "permissions": [
            "offscreen"
          ]
        }
        
  3. खुद ऑफ़स्क्रीन दस्तावेज़ बनाएं. यह आपके एक्सटेंशन पैकेज में मौजूद एक बहुत कम एचटीएमएल फ़ाइल है, जो आपके ऑफ़स्क्रीन दस्तावेज़ के JavaScript का लॉजिक लोड करती है:
  4.     <!DOCTYPE html>
        <script src="./offscreen.js"></script>
        
  5. अपने एक्सटेंशन पैकेज में offscreen.js को शामिल करें. यह पहले चरण में सेट अप की गई सार्वजनिक वेबसाइट और आपके एक्सटेंशन के बीच प्रॉक्सी के तौर पर काम करता है.
  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 से आपके सर्विस वर्कर के पास प्रॉक्सी कर दिया जाएगा.