mauriciovigolo / keycloak-angular

Easy Keycloak setup for Angular applications.
MIT License
730 stars 280 forks source link

Check if user is logged in before app is bootstrapped #486

Closed ibagaric closed 1 year ago

ibagaric commented 1 year ago

I want to check if user logged in before the app is bootstrapped, so I add keycloak.isLoggedIn() in APP_INITIALIZER, but it always returns false.

export function isUserLoggedIn(
  keycloak: KeycloakService
) {
  return async () => {
    const isLoggedIn = await keycloak.isLoggedIn();
    console.log(isLoggedIn);
    if (!isLoggedIn) {
      localStorage.clear();
    }
  };
}

export function appInit(
  keycloak: KeycloakService,
  auth: AuthenticationService,
) {
  return () =>
    keycloak
      .init({
        config: {
          url: environment.keycloakUrl + '/auth',
          realm: environment.keycloakRealm,
          clientId: environment.keycloakClientId
        },
        initOptions: {
          onLoad: 'login-required',
          silentCheckSsoRedirectUri: window.location.origin + '/assets/silent-check-sso.html'
        },
        enableBearerInterceptor: true,
      })

Bug Report or Feature Request (mark with an x)

- [x] bug report -> please search for issues before submitting
- [] feature request

Versions.

    "keycloak-angular": "^9.3.2",
    "keycloak-js": "^16.1.1",

Desired functionality.

I need to clear local storage before login if a user is not authenticated. Or maybe some other idea how to clean the local storage, if the user has logged out on another environment

mauriciovigolo commented 1 year ago

Hey @ibagaric, I think it could be related to the order of the execution of your application, not sure how it works since I don't have more details. Once the user is logged in keycloak.isLoggedIn() will return true. Please if you are facing the issue, could you provide an example so I could better understand? 

mauriciovigolo commented 1 year ago

Closing this issue since seems it is not a general problem. If you or someone faces an issue with this function please open a new ticket with an example so we can better evaluate. Thanks!