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?