简体   繁体   中英

How to logout from Angular app once Keycloak session is terminated using keycloak-angular

I am using keycloak-angular for my login page.

If I terminate a user's session from the Keycloak's admin panel I don't receive any event when doing:

this.keycloakService.keycloakEvents$.subscribe((event: KeycloakEvent) => {
  console.log(event);
});

The user can keep using the app until he clicks the refresh button. How can I log him out immediately?

i don't think this is possible. There is no WebSocket connection or equivalent open in order to get the events from the Admin page. In my opinion the only solution would to check the state periodically with a setInterval() but it's not a very elegant and performant solution

If you define that in for example AppComponent you will receive evens for example of type: OnTokenExpired to refresh automatically your token, but not he event OnAuthSuccess because this subsciption is made after the login so the last event never be triggered. I'm trying to workaround this problem know by the keycloak-angular guys.

A sample of that could be:

import { Component } from '@angular/core';
import { Router } from '@angular/router';

import { KeycloakService, KeycloakEvent, KeycloakEventType } from 'keycloak-angular';
import { KeycloakProfile } from 'keycloak-js';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  public title: String = 'Productland Portal';
  public isLoggedIn = false;
  public userProfile: KeycloakProfile | null = null;

  constructor(private readonly keycloakService: KeycloakService,
              private readonly router: Router,) {
      // configure token expiration handler
      keycloakService.keycloakEvents$.subscribe({
        next: (event: KeycloakEvent) => {
          if (event.type == KeycloakEventType.OnAuthSuccess) {
            this.router.navigateByUrl('/');
          }
          else if (event.type == KeycloakEventType.OnTokenExpired) {            
            console.log('Token refreshed at ' + new Date());

            keycloakService.updateToken(20);
          }
          else if (event.type == KeycloakEventType.OnAuthRefreshError) {
            this.router.navigateByUrl('/'); 
          }
        }
      });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM