I am evaluating using a JS ServiceWorkers as an identity proxy, injecting the access_token
on fetch()
calls using the javascript below:
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);
In this example the token
is stored in a variable within the serviceWorker class. Click here for more information about this approach.
One problem I am running into is that seemingly randomly something happens to the serviceWorker and the token
variable loses its value, 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?