4

I am using a plugin "keycloak-angular".

Version :

"keycloak-angular": "8.0.1",
"keycloak-js": "11.0.2",
angular : 9.1.12

I have set "Access token lifespan" to 1 minute. And I am trying to update Tokens when access token is expired by checking with Keycloak.isTokenExpired(). Its working but the issue that I am facing is, sometimes this function gets called and most of the time its not getting called. What I want to achieve -> Whenever the access token expires, I want to update the token, keeping the user logged-In. Tried to find this issue over the internet but couldn't find anything similar.

import {KeycloakService} from 'keycloak-angular';

export function initializer(keycloak: KeycloakService) {
  return () => {
    return new Promise(async (resolve, reject) => {
      try {
        const _REALM = "realm";
        const _URL = "http://example.com";
        const _CLIENT_ID = "id"

    await keycloak.init({
      config: {
        realm: _REALM,
        url: _URL,
        clientId: _CLIENT_ID,
      },
      initOptions: {
        onLoad: 'login-required',
        checkLoginIframe: false
      },
      enableBearerInterceptor: true,
      bearerExcludedUrls: ['/assets', '/clients/public']
    })

    const keycloakAuth = keycloak.getKeycloakInstance();

    const updateToken = async (): Promise < string > => {
      const {success,error} = keycloakAuth.updateToken(5);
      return new Promise < string > ((res, rej) => {
        success(() => res(keycloakAuth.token));
        error(rej);
      });
    }
    const login = async (): Promise < void > => {
      const {success,error} = keycloakAuth.login();
      return new Promise < void > ((res2, rej2) => {
        success(res2);
        error(rej2);
      });
    }


    keycloakAuth.onTokenExpired = () => {
      if (keycloakAuth.refreshToken) {
        updateToken();
      } else {
        login();
      }
    }

    resolve();
  } catch (error) {
    reject(error);
  }
});

}; }

This is the code I am using, its placed in app-init.ts.

getting this from network tab -

expires_in: 60
refresh_expires_in: 1800

Screenshot of provider in main module file. Provider in main module

PS- New to this, apologies if there is a mistake in question or if i left something

vahid tajari
  • 1,163
  • 10
  • 20
Faiz
  • 41
  • 1
  • 3

2 Answers2

2

(refreshed) returns false only if your token is not expired. So you're trying to refresh the token when it has not yet expired.

try the following code to check the status of refreshed again

    keycloak.onTokenExpired = ()=>{
            console.log('expired '+new Date());
            keycloak.updateToken(50).success((refreshed)=>{
                if (refreshed){
                    console.log('refreshed '+new Date());
                }else {
                    console.log('not refreshed '+new Date());
                }
            }).error(() => {
                 console.error('Failed to refresh token '+new Date());
            });
            }
Palak Jadav
  • 1,202
  • 1
  • 11
  • 23
  • Thank you for the response, I am still confused as to why the token does'nt expires sometimes? Like sometime when user logs-in and is redirected to homepage, token expires in a minute as it is supposed to. But at times, token doesn't expire and logic written "keycloak.onTokenExpired" never gets executed. – Faiz Nov 02 '20 at 10:00
  • "But at times, token doesn't expire and logic written "keycloak.onTokenExpired" never gets executed." What specifically are you seeing or not seeing? Is the user getting logged out but you're expecting the session to refresh? Is the session getting refreshed but you're expecting a logout? Is there a console.log statement at the beginning of the callback that's just never executed? – solidparallel Dec 22 '22 at 10:18
0

For Keycloack version 19 use,

    _kc.updateToken(5)
    .then(function(refreshed) {
        if (refreshed) {
            alert('Token was successfully refreshed');
        } else {
            alert('Token is still valid');
        }
    }).catch(function() {
        alert('Failed to refresh the token, or the session has expired');
    });
Ali-Alrabi
  • 1,515
  • 6
  • 27
  • 60