w3c / w3c/ServiceWorker

How to handle redirected URL for login authentication offline.

Open
#1,226 10 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Bikeshed
Stars
3.6k
Forks
324
Avg merge
14d 22h
Merged PRs (30d)
1

Description

Hi Team,
I am using PWA in my angular-5 application, supported by angular-cli and I am using Keycloak for login authentication. The application works well offline, but one issue I am facing. While reloading the authenticator tries to find the login status from the Keycloak server and fails due to the internet connection.

Below is my service-worker:

`


var dataCacheName = 'resourceAllo-v1';
var cacheName = 'resourceAlloPWA-final-1';

var filesToCache = [
    '/',
    '/index.html',
    '/favicon.png',
    './app/app.component.html',
];

self.addEventListener('install', function(e) {
    console.log('[ServiceWorker] Install');
    e.waitUntil(
        caches.open(cacheName).then(function(cache) {
            console.log('[ServiceWorker] Caching app shell');
            return cache.addAll(filesToCache);
        })
    );
});

self.addEventListener('activate', function(e) {
    console.log('[ServiceWorker] Activate');
    e.waitUntil(
        caches.keys().then(function(keyList) {
            return Promise.all(keyList.map(function(key) {
                if (key !== cacheName && key !== dataCacheName) {
                    console.log('[ServiceWorker] Removing old cache', key);
                    return caches.delete(key);
                }
            }));
        })
    );
    
    return self.clients.claim();
});
self.addEventListener('opaqueredirect', function(e) {
    debugger
    console.log('[Service Worker] redirect ', e);
})

self.addEventListener('fetch', function(e) {
    console.log('[Service Worker] Fetch', e.request.url);
    var dataUrl = 'https://keycloak-server-connect/userinfo';
    var tokenUrl = 'https://keycloak-server-connect/protocol/openid-connect/token';
    var cssUrl = 'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css';
    var keycloakUrl = 'https://keycloak-server-connect/auth/realms/abc/protocol/openid-connect/auth?client_id=service&redirect_uri=http%3A%2F%2Flocalhost%3A4200%2F&state=de9b09b0-d14e-408c-bf11-90c461861a57&nonce=a390644f-f3ca-4aff-be76-a23ef130e101&response_mode=fragment&response_type=code&scope=openid';

    if (e.request.url.indexOf(dataUrl) > -1) {
       
        e.respondWith(
            caches.open(cacheName).then(function(cache) {
                return fetch(e.request).then(function(response) {
                    cache.put(e.request.url, response.clone());
                    return response;
                });
            })
        );
    } else if (e.request.url.indexOf(cssUrl) > -1) {
        e.respondWith(
            caches.open(cacheName).then(function(cache) {
                return fetch(e.request).then(function(response) {
                    cache.put(e.request.url, response.clone());
                    return response;
                });
            })
        );
    } else if (e.request.url.indexOf(keycloakUrl) > -1) {
        e.respondWith(
            caches.open(cacheName).then(function(cache) {
                return fetch(e.request).then(function(response) {
                    cache.put(e.request.url, response.clone());
                    return response;
                });
            })
        )
    } else {
       
        var updateCache = function(request) {
            if (request.url != dataUrl && request.url != tokenUrl) {
                return caches.open(cacheName).then(function(cache) {
                    return fetch(request).then(function(response) {
                        console.log('[PWA Builder] add page to offline ' + response.url)
                        return cache.put(request, response);
                    });
                });
            }
        };

        e.waitUntil(updateCache(e.request.clone()));
        e.respondWith(
            caches.match(e.request).then(function(response) {
                return response || fetch(e.request);
            }).catch(function() {
                console.log('[Service Worker] event', e);
                // If both fail, show a generic fallback:
                return caches.match('/offline.html');
            })
        )
    }
});` 

And my main.js:

`if (navigator.serviceWorker.controller) {
            console.log('[PWA Builder] active service worker found, no need to register')
        } else {
            navigator.serviceWorker.register('service-worker.js', {
                scope: './'
            }).then(function(reg) {
                console.log('Service worker has been registered for scope:' + reg.scope);
            });
        }`

Please help me out on this. Let me know if any info is needed.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Read the supplied service-worker.js fetch handler and main.js registration first, then trace the Keycloak redirect and authentication-status requests during an offline reload. Confirm which request fails and define the expected login behavior before determining whether the change belongs in service-worker handling or application authentication.

Written by the indexing model from the issue text.

Assessment

Tech stack
angular, javascript
Domain
authentication, web-dev
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.