ניהול סשנים עם קובצי שירות (service worker)

ב-Firebase Auth אפשר להשתמש ב-Service Workers כדי לזהות ולהעביר טוקנים של מזהה של Firebase לניהול סשנים. היתרונות של השיטה הזו:

  • אפשרות להעביר טוקן של מזהה בכל בקשת HTTP מהשרת בלי עבודה נוספת.
  • אפשרות לרענן את הטוקן של המזהה בלי זמן אחזור או סבב נוסף.
  • סשנים מסונכרנים בקצה העורפי ובקצה הקדמי. הפתרון הזה מתאים לאפליקציות שצריכות לגשת לשירותי Firebase כמו מסד נתונים בזמן אמת,‏ Firestore וכו', ולמשאבים מסוימים בצד השרת (מסד נתונים של SQL וכו'). בנוסף, אפשר לגשת לאותו סשן גם מ-service worker, מ-web worker או מ-shared worker.
  • מבטל את הצורך לכלול את קוד המקור של Firebase Auth בכל דף (מפחית את זמן האחזור). ה-Service Worker, שנטען ומאותחל פעם אחת, יטפל בניהול הסשנים של כל הלקוחות ברקע.

סקירה כללית

‫Firebase Auth מותאם להפעלה בצד הלקוח. האסימונים נשמרים באחסון באינטרנט. כך קל לשלב גם שירותים אחרים של Firebase, כמו מסד נתונים בזמן אמת, Cloud Firestore, Cloud Storage וכו'. כדי לנהל סשנים מנקודת המבט של צד השרת, צריך לאחזר טוקנים של מזהים ולהעביר אותם לשרת.

Web

import { getAuth, getIdToken } from "firebase/auth";

const auth = getAuth();
getIdToken(auth.currentUser)
  .then((idToken) => {
    // idToken can be passed back to server.
  })
  .catch((error) => {
    // Error occurred.
  });

Web

firebase.auth().currentUser.getIdToken()
  .then((idToken) => {
    // idToken can be passed back to server.
  })
  .catch((error) => {
    // Error occurred.
  });

עם זאת, המשמעות היא שצריך להריץ סקריפט כלשהו מהלקוח כדי לקבל את טוקן של מזהה העדכני, ואז להעביר אותו לשרת דרך request header, גוף ה-POST וכו'.

יכול להיות שהשיטה הזו לא תתאים לכל המקרים, ויהיה צורך בקובצי Cookie זמניים בצד השרת. אפשר להגדיר טוקנים של מזהים כקובצי Cookie זמניים, אבל הם קצרי מועד וצריך לרענן אותם מהלקוח ואז להגדיר אותם כקובצי Cookie חדשים כשהתוקף שלהם פג. יכול להיות שזה ידרוש עוד נסיעה הלוך ושוב אם המשתמש לא ביקר באתר כבר זמן מה.

למרות ש-Firebase Auth מספק פתרון מסורתי יותר לניהול סשנים שמבוסס על קובצי Cookie, הפתרון הזה מתאים במיוחד לאפליקציות httpOnly שמבוססות על קובצי Cookie בצד השרת, וקשה יותר לנהל אותו כי יכול להיות שהאסימונים בצד הלקוח והאסימונים בצד השרת לא יהיו מסונכרנים, במיוחד אם צריך להשתמש גם בשירותים אחרים של Firebase שמבוססים על הלקוח.

במקום זאת, אפשר להשתמש ב-service workers כדי לנהל סשנים של משתמשים בצד השרת. זה עובד מהסיבות הבאות:

  • ל-Service Workers יש גישה למצב הנוכחי של Firebase Auth. אפשר לאחזר את טוקן המזהה של המשתמש הנוכחי מ-Service Worker. אם פג התוקף של האסימון, ערכת ה-SDK של הלקוח תרענן אותו ותחזיר אסימון חדש.
  • קובצי שירות יכולים ליירט בקשות אחזור ולשנות אותן.

שינויים בקובצי שירות (service worker)

ה-service worker צריך לכלול את ספריית האימות ואת היכולת לקבל את אסימון המזהה הנוכחי אם המשתמש מחובר.

Web

import { initializeApp } from "firebase/app";
import { getAuth, onAuthStateChanged, getIdToken } from "firebase/auth";

// Initialize the Firebase app in the service worker script.
initializeApp(config);

/**
 * Returns a promise that resolves with an ID token if available.
 * @return {!Promise<?string>} The promise that resolves with an ID token if
 *     available. Otherwise, the promise resolves with null.
 */
const auth = getAuth();
const getIdTokenPromise = () => {
  return new Promise((resolve, reject) => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      unsubscribe();
      if (user) {
        getIdToken(user).then((idToken) => {
          resolve(idToken);
        }, (error) => {
          resolve(null);
        });
      } else {
        resolve(null);
      }
    });
  });
};

Web

// Initialize the Firebase app in the service worker script.
firebase.initializeApp(config);

/**
 * Returns a promise that resolves with an ID token if available.
 * @return {!Promise<?string>} The promise that resolves with an ID token if
 *     available. Otherwise, the promise resolves with null.
 */
const getIdToken = () => {
  return new Promise((resolve, reject) => {
    const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
      unsubscribe();
      if (user) {
        user.getIdToken().then((idToken) => {
          resolve(idToken);
        }, (error) => {
          resolve(null);
        });
      } else {
        resolve(null);
      }
    });
  });
};

כל בקשות השליפה למקור של האפליקציה יופסקו, ואם יהיה זמין טוקן של מזהה, הוא יצורף לבקשה דרך הכותרת. בצד השרת, כותרות הבקשה ייבדקו כדי לאתר את טוקן של מזהה, יאומתו ויעובדו. בסקריפט של קובץ השירות (service worker), בקשת האחזור תופסק ותשתנה.

Web

const getOriginFromUrl = (url) => {
  // https://stackoverflow.com/questions/1420881/how-to-extract-base-url-from-a-string-in-javascript
  const pathArray = url.split('/');
  const protocol = pathArray[0];
  const host = pathArray[2];
  return protocol + '//' + host;
};

// Get underlying body if available. Works for text and json bodies.
const getBodyContent = (req) => {
  return Promise.resolve().then(() => {
    if (req.method !== 'GET') {
      if (req.headers.get('Content-Type').indexOf('json') !== -1) {
        return req.json()
          .then((json) => {
            return JSON.stringify(json);
          });
      } else if (
        req.headers.get('Content-Type').indexOf('multipart/form-data') !== -1
      ) {
        return req.clone().arrayBuffer();
      } else {
        return req.text();
      }
    }
  }).catch((error) => {
    // Ignore error.
  });
};

self.addEventListener('fetch', (event) => {
  /** @type {FetchEvent} */
  const evt = event;

  const requestProcessor = (idToken) => {
    let req = evt.request;
    let processRequestPromise = Promise.resolve();
    // For same origin https requests, append idToken to header.
    if (self.location.origin == getOriginFromUrl(evt.request.url) &&
        (self.location.protocol == 'https:' ||
         self.location.hostname == 'localhost') &&
        idToken) {
      // Clone headers as request headers are immutable.
      const headers = new Headers();
      req.headers.forEach((val, key) => {
        headers.append(key, val);
      });
      // Add ID token to header.
      headers.append('Authorization', 'Bearer ' + idToken);
      processRequestPromise = getBodyContent(req).then((body) => {
        try {
          req = new Request(req.url, {
            method: req.method,
            headers: headers,
            mode: 'same-origin',
            credentials: req.credentials,
            cache: req.cache,
            redirect: req.redirect,
            referrer: req.referrer,
            body,
            // bodyUsed: req.bodyUsed,
            // context: req.context
          });
        } catch (e) {
          // This will fail for CORS requests. We just continue with the
          // fetch caching logic below and do not pass the ID token.
        }
      });
    }
    return processRequestPromise.then(() => {
      return fetch(req);
    });
  };
  // Fetch the resource after checking for the ID token.
  // This can also be integrated with existing logic to serve cached files
  // in offline mode.
  evt.respondWith(getIdTokenPromise().then(requestProcessor, requestProcessor));
});

Web

const getOriginFromUrl = (url) => {
  // https://stackoverflow.com/questions/1420881/how-to-extract-base-url-from-a-string-in-javascript
  const pathArray = url.split('/');
  const protocol = pathArray[0];
  const host = pathArray[2];
  return protocol + '//' + host;
};

// Get underlying body if available. Works for text and json bodies.
const getBodyContent = (req) => {
  return Promise.resolve().then(() => {
    if (req.method !== 'GET') {
      if (req.headers.get('Content-Type').indexOf('json') !== -1) {
        return req.json()
          .then((json) => {
            return JSON.stringify(json);
          });
      } else if (
        req.headers.get('Content-Type').indexOf('multipart/form-data') !== -1
      ) {
        return req.clone().arrayBuffer();
      } else {
        return req.text();
      }
    }
  }).catch((error) => {
    // Ignore error.
  });
};

self.addEventListener('fetch', (event) => {
  /** @type {FetchEvent} */
  const evt = event;

  const requestProcessor = (idToken) => {
    let req = evt.request;
    let processRequestPromise = Promise.resolve();
    // For same origin https requests, append idToken to header.
    if (self.location.origin == getOriginFromUrl(evt.request.url) &&
        (self.location.protocol == 'https:' ||
         self.location.hostname == 'localhost') &&
        idToken) {
      // Clone headers as request headers are immutable.
      const headers = new Headers();
      req.headers.forEach((val, key) => {
        headers.append(key, val);
      });
      // Add ID token to header.
      headers.append('Authorization', 'Bearer ' + idToken);
      processRequestPromise = getBodyContent(req).then((body) => {
        try {
          req = new Request(req.url, {
            method: req.method,
            headers: headers,
            mode: 'same-origin',
            credentials: req.credentials,
            cache: req.cache,
            redirect: req.redirect,
            referrer: req.referrer,
            body,
            // bodyUsed: req.bodyUsed,
            // context: req.context
          });
        } catch (e) {
          // This will fail for CORS requests. We just continue with the
          // fetch caching logic below and do not pass the ID token.
        }
      });
    }
    return processRequestPromise.then(() => {
      return fetch(req);
    });
  };
  // Fetch the resource after checking for the ID token.
  // This can also be integrated with existing logic to serve cached files
  // in offline mode.
  evt.respondWith(getIdToken().then(requestProcessor, requestProcessor));
});

כתוצאה מכך, כל הבקשות המאומתות תמיד יכללו טוקן של מזהה שמועבר בכותרת ללא עיבוד נוסף.

כדי ש-Service Worker יזהה שינויים במצב האימות, צריך להתקין אותו בדף הכניסה או ההרשמה. חשוב לוודא ש-Service Worker מקובץ כדי שהוא ימשיך לפעול אחרי שהדפדפן נסגר.

אחרי ההתקנה, ה-service worker צריך להפעיל את clients.claim() בזמן ההפעלה כדי שיוגדר כבקר של הדף הנוכחי.

Web

self.addEventListener('activate', (event) => {
  event.waitUntil(clients.claim());
});

Web

self.addEventListener('activate', (event) => {
  event.waitUntil(clients.claim());
});

שינויים בצד הלקוח

אם יש תמיכה בקובץ השירות (service worker), צריך להתקין אותו בדף הכניסה/ההרשמה בצד הלקוח.

Web

// Install servicerWorker if supported on sign-in/sign-up page.
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js', {scope: '/'});
}

Web

// Install servicerWorker if supported on sign-in/sign-up page.
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js', {scope: '/'});
}

כשהמשתמש מחובר ומופנה לדף אחר, ה-service worker יוכל להוסיף את הטוקן של המזהה לכותרת לפני שההפניה האוטומטית תושלם.

Web

import { getAuth, signInWithEmailAndPassword } from "firebase/auth";

// Sign in screen.
const auth = getAuth();
signInWithEmailAndPassword(auth, email, password)
  .then((result) => {
    // Redirect to profile page after sign-in. The service worker will detect
    // this and append the ID token to the header.
    window.location.assign('/profile');
  })
  .catch((error) => {
    // Error occurred.
  });

Web

// Sign in screen.
firebase.auth().signInWithEmailAndPassword(email, password)
  .then((result) => {
    // Redirect to profile page after sign-in. The service worker will detect
    // this and append the ID token to the header.
    window.location.assign('/profile');
  })
  .catch((error) => {
    // Error occurred.
  });

שינויים בצד השרת

הקוד בצד השרת יוכל לזהות את אסימון המזהה בכל בקשה. ההתנהגות הזו נתמכת על ידי Admin SDK ל-Node.js או עם Web SDK באמצעות FirebaseServerApp.

Node.js

  // Server side code.
  const { initializeApp } = require('firebase-admin/app');
  const { getAuth } = require('firebase-admin/auth');

  // The Firebase Admin SDK is used here to verify the ID token.
  initializeApp();

  function getIdToken(req) {
    // Parse the injected ID token from the request header.
    const authorizationHeader = req.headers.authorization || '';
    const components = authorizationHeader.split(' ');
    return components.length > 1 ? components[1] : '';
  }

  function checkIfSignedIn(url) {
    return (req, res, next) => {
      if (req.url == url) {
        const idToken = getIdToken(req);
        // Verify the ID token using the Firebase Admin SDK.
        // User already logged in. Redirect to profile page.
        getAuth().verifyIdToken(idToken).then((decodedClaims) => {
          // User is authenticated, user claims can be retrieved from
          // decodedClaims.
          // In this sample code, authenticated users are always redirected to
          // the profile page.
          res.redirect('/profile');
        }).catch((error) => {
          next();
        });
      } else {
        next();
      }
    };
  }

  // If a user is signed in, redirect to profile page.
  app.use(checkIfSignedIn('/'));

Web modular API

import { initializeServerApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { headers } from 'next/headers';
import { redirect } from 'next/navigation';

export default function MyServerComponent() {

    // Get relevant request headers (in Next.JS)
    const authIdToken = headers().get('Authorization')?.split('Bearer ')[1];

    // Initialize the FirebaseServerApp instance.
    const serverApp = initializeServerApp(firebaseConfig, { authIdToken });

    // Initialize Firebase Authentication using the FirebaseServerApp instance.
    const auth = getAuth(serverApp);

    if (auth.currentUser) {
        redirect('/profile');
    }

    // ...
}

סיכום

בנוסף, מכיוון שהטוקנים של המזהים יוגדרו דרך ה-Service Workers, וה-Service Workers מוגבלים להפעלה מאותו מקור, אין סיכון ל-CSRF כי אתר ממקור אחר שינסה לקרוא לנקודות הקצה שלכם לא יצליח להפעיל את ה-Service Worker, והבקשה תיראה לא מאומתת מנקודת המבט של השרת.

למרות ש-Service Workers נתמכים עכשיו בכל הדפדפנים המודרניים המובילים, חלק מהדפדפנים הישנים יותר לא תומכים בהם. כתוצאה מכך, יכול להיות שתצטרכו להשתמש בגיבוי כדי להעביר את הטוקן של המזהה לשרת כש-Service Workers לא זמינים, או להגביל את האפליקציה כך שתפעל רק בדפדפנים שתומכים ב-Service Workers.

חשוב לזכור שקובצי השירות הם ממקור יחיד בלבד, והם יותקנו רק באתרים שמוצגים דרך חיבור HTTPS או localhost.

מידע נוסף על תמיכה של דפדפנים בקובצי שירות (service worker) זמין בכתובת caniuse.com.