Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keycloak redirects to login on page refresh

I am using keycloak JavaScript adapter in my Angular 5 app and whilst my login and redirection works, the problem is that whenever I refresh my ng app it will again ask for keycloak login altough I see that my session is still active on /auth/realms/{image a realm name}/account.

As I have understood it from the keycloak JS Adapter documentation https://www.keycloak.org/docs/3.0/securing_apps/topics/oidc/javascript-adapter.html, when onLoad is set to login-required for init options it authenticates the client if the user is logged-in to Keycloak or display the login page if not. But it seems like, in my case, that it takes one second to log me out because it always redirects me to the keycloak's login page.

like image 336
Random Stuff Avatar asked May 29 '18 09:05

Random Stuff


1 Answers

You need to pass the saved token from previous login to keycloak init constructor. If you are using Authorization Flow (standard) then refresh token as well. Like this.

// load previous tokens, saved after successful login of keycloak success callback
    const token = localStorage.getItem('kc_token');
    const refreshToken = localStorage.getItem('kc_refreshToken');
    // pass to keycloak init
    keycloak.init({ onLoad: 'login-required', token, refreshToken }).then(
    success=>{
      localStorage.setItem('kc_token', keycloak.token);
      localStorage.setItem('kc_refreshToken', keycloak.refreshToken);
      //load your app from here
  });
like image 194
ahmadalibaloch Avatar answered Nov 15 '22 00:11

ahmadalibaloch