Skip to content

CodeCoupler Application Basics Combine service-worker and oidc 🔒

If you want to combine the Service Worker Loader with your own service worker and the OIDC Authentication Library, you just need to load your own service worker and import the OIDC service worker:

self.importScripts("OidcServiceWorker.js");

Preparations

After that, a few things need to be taken into account:

(1) If you are using oidc-client version 7.24 or below you must remove its event listeners install and activate:

self.removeEventListener("install", handleInstall);
self.removeEventListener("activate", handleActivate);

(2) Your own service worker has to listen to the message that'll trigger self.skipWaiting(). Here an example listening to the message { codecoupler: "cc-skip-message" }:

1
2
3
4
5
6
7
8
self.addEventListener("message", (messageEvent) => {
  switch (messageEvent.data?.codecoupler) {
    case "cc-skip-waiting": {
      self.skipWaiting();
      break;
    }
  }
});

(3) Important: Do not use self.addEventListener("fetch", (e) => {}) in your own service worker. Or ensure at least you do not call respondWith() inside of your listener when the authentication or the resource server is requested.

Usage

Then you can load your own service worker with this configuration:

import { AuthOidc } from "@codecoupler-pro/app-oidc";
import { ServiceWorkerLoader } from "@codecoupler-pro/app-service-worker";
let swLoader = new ServiceWorkerLoader({ serviceWorkerUrl: "sw-oidc.js" });
let auth = new AuthOidc({
  // If you use oidc-client in version 7.22 or below:
  // register: true,
  // Add this to the configuration of the OIDC Authentication Library:
  service_worker_register: async () => {
    return (await swLoader.promise).registration;
  }
});
if (!auth.insidePopup) {
  // Build your UI here. Mostly the callbacks of the service worker
  // loader will be used here to give feedback to UI elements:
  swLoader.promise.then(callbackRegistered).catch(callbackRegistrationFailed);
  swLoader.updateFound.then(callbackUpdateFound);
}

You have to pay attention whenever you send a message to your own service worker you've got to add the property configurationName to the message data object. Instead of:

1
2
3
serviceWorkerInstance.postMessage({
  codecoupler: "cc-get-version"
});

You have to post:

1
2
3
4
serviceWorkerInstance.postMessage({
  codecoupler: "cc-get-version",
  configurationName: "default"
});

This is because the event handler of the OIDC library will also catch these messages. If there isn't a configuration name (which is specified in OidcTrustedDomains.js), it'll run into an exception.