Keycloak on Angular - not getting correct status on load

3.6k Views Asked by At

Using latest angular (11), latest keycloak-angular and keycloak-js.

On page load, when I initialize keycloak I want to get loggedin status. I'm getting always false, even if the session is active.

This is my initializer code:

import { KeycloakService } from 'keycloak-angular';
import { AppService } from 'src/app/app.service';
import { environment } from '../environments/environment';
 
export function initializer(keycloak: KeycloakService, appService: AppService): () => Promise<any> {
    return (): Promise<any> => {
        return new Promise<void>(async (resolve, reject) => {
          try {
            await keycloak.init({
                config: {
                    url: environment.keycloak.issuer,
                    realm: environment.keycloak.realm,
                    clientId: environment.keycloak.clientId
                },
              loadUserProfileAtStartUp: true,
              initOptions: {
                checkLoginIframe: true
              },
              bearerExcludedUrls: []
            }).then((a) => {
              console.log(a); // this returns always false
            });
            resolve();
          } catch (error) {
            reject(error);
          }
        });
      };
}

This returns false even if: enter image description here

3

There are 3 best solutions below

3
On

I would say it needs grant code with pkce flow first, because it's SPA (of course used OIDC client must be public):

initOptions: {
  onLoad: 'login-required',
  checkLoginIframe: false,
  pkceMethod: 'S256'
},

Also async/await syntax can be a problem (but Angular/JS is not my cup of tea, so I can be wrong). I would rewrite it to:

keycloak.init(
  ...
).then(async authenticated => {
  if (!authenticated) {
    // unauthenticated
    console.log(a)
    window.location.reload()
    return
  } else {
    // authenticated
    console.log(a)
    ...
  }
0
On

As I wrote in my comments, I found that I have to have onLoad property. I did not want to have onLoad: 'login-required', because users are not required to be logged in for most of pages, so I had to add onLoad: 'check-sso'.

1
On

Please try with this initilizer method:

export function initializer(keycloak: KeycloakService): () => Promise<any> {
return (): Promise<any> => {
  return new Promise(async (resolve, reject) => {
    try {
      await keycloak.init({
        config: {
                url: environment.keycloak.issuer,
                realm: environment.keycloak.realm,
                clientId: environment.keycloak.clientId
            },
        initOptions: {
          onLoad: 'check-sso',
          checkLoginIframe: false
        },
        enableBearerInterceptor: true,
        bearerPrefix: 'Bearer',
        bearerExcludedUrls: [
          'main.js',
        ]
      });
      resolve();
    } catch (error) {
      reject(error);
    }
  }
    )
    .catch((e) => {
      console.log('Error thrown in init ' + e);
    });
};
}