Login guard Keycloak and angular

465 Views Asked by At

I am using keycloak-angular in my project I want to implement a login guard to prevent authenticated users from navigating to public pages like the login page and register. I tried to implement it like below but it just redirects to the public area.

export class LoginGuard extends KeycloakAuthGuard {
  constructor(protected override readonly router: Router, protected readonly keycloak: KeycloakService) {
    super(router, keycloak);
  }

  async isAccessAllowed(): Promise<boolean | UrlTree> {
    const isLoggedIn = await this.keycloak.isLoggedIn();
    if(isLoggedIn){
      this.router.navigate(['/']);
      return false;
    }
    return true;
  }
}

isLoggedIn is always false even if the user authenticated.

1

There are 1 best solutions below

0
On

Put the code in try/catch block

async isAccessAllowed(): Promise<boolean|UrlTree> {
  try {
    const isLoggedIn = await this.keycloak.isLoggedIn();
    if(!isLoggedIn) return;
  
    this.router.navigate(['/']);
    return false;
  } catch(error) {

  }
}