2018-07-16

Service worker and 401 authorization

What happens


  • The website area (/admin) is protected by an `htpasswd` authorization (Apache: AuthType Basic, Require valid-user, etc.).
  • A "standard" service worker script is loaded at the home page, doing its usual stuff (install, fetch, cache).
  • When you go to the protected page, you are not asked for the user/password, but see the "Not Authorized" message immediately.
  • If you clear the service worker (in Chrome, F12 - Application - Clear storage), you can enter the admin area.

One way to cure

Your service-worker.js script probably has a piece of code that looks like:

self.addEventListener('fetch', event => {
    // Let the browser do its default thing
    // for non-GET requests.
    if (event.request.method !== 'GET') {
        return;
    }

Add the following lines immediately after that part:

    // Exclude admin panel.
    if (0 === event.request.url.indexOf("https://www.my-site.com/admin")) {
        return;
    }

It should help.