0

I am evaluating using a JS ServiceWorkers as an identity proxy, injecting the access_token on fetch() calls.

const addAuthHeader = function (event) {
    destURL = new URL(event.request.url);
    if (whitelistedOrigins.includes(destURL.origin) && whitelistedPathRegex.test(destURL.pathname)) {
        const modifiedHeaders = new Headers(event.request.headers);
        if (token) {
           modifiedHeaders.append('Authorization', token) //< Injection
        }
        const authReq = new Request(event.request, {headers: modifiedHeaders, mode: 'cors' });
        event.respondWith((async () => fetch(authReq))());
    }
}

// Intercept all fetch requests and add the auth header
self.addEventListener('fetch', addAuthHeader);

The token is stored in a closure variable within the serviceWorker class. Click here for more information about this approach.

One problem I am running into is that when the serviceWorker is updated, the token variable is being overwritten and the access_token is lost.

Is there a way to detect that the serviceWorker has been updated? Or, to protect the token variable? Is there a design pattern/standard you can point me towards related to using serviceWorker as an identity proxy as I have done?

user1913559
  • 301
  • 1
  • 13

1 Answers1

0

I would advise against an approach that requires a service worker to be in control of a given page for anything security/identity related.

First off, users who visit your page for the first time will not have a service worker installed yet, so it won't be in control of the current page. Additionally, users who are familiar with the browser's developer tools can unregister a service worker at any time, and/or use shift-reload to visit your page without the active service worker in control. So you really can't rely on the service worker always being there.

Second, a service worker's global state is short-lived, and you can't rely on variables being present across multiple event invocations. There are more details about that in "When does code in a service worker outside of an event handler run?".

Generally speaking, you should consider the behavior inside of a service worker as progressively enhancing the core functionality of your web app, and not move any required functionality to the service worker.

Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167