keycloak-js initialization using Angular

61 Views Asked by At

I have been integrating keycloak-js and angular to achieve the following scenario in a multitenant application:

  • The /signing page is public (Without Guard rules) and displays a form were the user manually type the Keycloak Realm, like the following example:

enter image description here

  • When he clicks the button confirm, the component stores the Realm in the SessionStorage and calls a service SecurityService to manage the login using the method signIn

  • The user is redirected to the Keycloak Login page to input the credentials, then is redirected to the /home page of the application.

  • Everything works fine but I want to know if it is possible to initialize and update the value of the keycloak property in the SecurityService without the need of the method init every time I want to use it, because it is defined empty by default keycloak: Keycloak = new Keycloak(); I need to execute this.keycloak = new Keycloak....

SecurityService.ts

import {Injectable} from '@angular/core';
import Keycloak from "keycloak-js";

@Injectable({
  providedIn: 'root'
})
export class SecurityService {

  keycloak: Keycloak = new Keycloak();

  constructor() {
  }

  init(): void {
    try {
      const realm = sessionStorage.getItem('realm') || '';
      this.keycloak = new Keycloak({
        url: 'http://mykeycloakserver:8080/',
        realm: realm,
        clientId: realm
      });
    } catch (e) {
      console.log('Failed to initialize', e);
    }
  }

  signIn() {
    this.init();
    this.keycloak.init({
      onLoad: 'login-required',
      pkceMethod: 'S256',
      redirectUri: window.location.origin + '/home',
    });
  }

  signOut() {
    this.init();
    this.keycloak.init({
      onLoad: 'check-sso',
      pkceMethod: 'S256'
    });

    const logout = this.keycloak.logout();
    sessionStorage.clear();
  }

  /**
   * SignIn the user after the redirect from KeyCloak server
   * @return a Promise<boolean> with the result
   */
  async isSignedIn(): Promise<boolean> {
    this.init();
    if (!this.keycloak) {
      return false;
    }
    let signedIn: boolean = false;
    try {
      signedIn = await this.keycloak.init({
        onLoad: 'check-sso',
        pkceMethod: 'S256',
        checkLoginIframe: false
      });
    } catch (e) {
      console.log('Failed to authenticate', e);
      return signedIn;
    }

    if (signedIn) {
      sessionStorage.setItem('jwt', <string>this.keycloak.token);
      sessionStorage.setItem('refresh-token', <string>this.keycloak.refreshToken);
    } else {
      sessionStorage.clear();
    }
    return signedIn;
  }
}

0

There are 0 best solutions below