Search code examples
angularauthorizationidentityserver4session-storageoidc-client-js

Angular application with oidc-client.js requires to login in second tab


I have authorization in Angular 8 handled by (oidc-client.js) + .Net Core IdentityServer4.

Everything seems to work fine, but when I open the same application in second tab then it requires from me to login again. IdentityServer4 has cookie so it's enough to click Login button and new token will be received without providing login/password again. Anyway it's still annoying.

Is it any way to solve it? I found question on githubg that might be partially helpful.

Some people suggesting that need to change token localization from LocalStorage to SessionStorage. But personally SessionStorage is better and I would keep it in that place.


Solution

  • If you like to use the SessionStorage (which seems to be correct) in several tabs, you could either copy its data between the tabs, for instance using LocalStorage event (see the code sample below) or BroadcastChannel, as described in this Q&A, or implement autologin, like an alternative solution does.

    (function(){
    
        if (!sessionStorage.length) {
            // trigger the event to get anything from other tabs
            localStorage.setItem('getSessionStorage', Date.now());
        };
    
        window.addEventListener('storage', function(event) {
    
        if (event.key == 'getSessionStorage') {
    
            //set and remove, so do not really keep the data in LS, but push it into event 
            localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
            localStorage.removeItem('sessionStorage');
    
        } else if (event.key == 'sessionStorage' && !sessionStorage.length) {
    
            var data = JSON.parse(event.newValue);
    
            for (key in data) {
                sessionStorage.setItem(key, data[key]);
            }
        }
    });