Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keycloak-angular: Multi-tenant application

I have installed keycloak-angular package and i use it just like the description of this: https://www.npmjs.com/package/keycloak-angular

The problem is that in my application i would like to have multi-tenant. This means that the realm name is not known during the application load.

In the instructions it says "The KeycloakService should be initialized during the application loading, using the APP_INITIALIZER token", the problem is that the realm is being given by the user and it is not accessible during the app initialization.

Is there any suggestion how can i set the realm string during the runtime of my application and not during application load?

like image 555
Nick6707 Avatar asked Nov 20 '25 02:11

Nick6707


1 Answers

i have achieved this by a work around and a default realm to initialize the app ,first create a pre login page , this page used to select realem manually or by calling api depending on user entry, also this page should be excluded from auth guard , at the action of pre login page save the selected realm in local storage and initialize keycloack service again with the new realm . app initializer code

return keycloak.init({
  config: {
    url: environment.authUrl,
    realm: window.localStorage.getItem('realm') || 'default',
    clientId: window.localStorage.getItem('client') || 'default',
  },
  initOptions: {
    onLoad: 'check-sso',
    checkLoginIframe: true,
    checkLoginIframeInterval: 5,
  },
  loadUserProfileAtStartUp: true,
  enableBearerInterceptor: true,
});

pre login page action

submitForm() {
  if (this.preloginForm.valid) {
    this.authService.getMapping(this.preloginForm.value.email).subscribe((res) => {
      localStorage.setItem('realm', res.realmId);
      localStorage.setItem('client', res.clientId);
      const config = {
        url: environment.authUrl,
        realm: res.realmId,
        clientId: res.clientId
      };
      this.keycloakService.init({
        config,
        initOptions: {
          onLoad: 'check-sso',
          checkLoginIframe: true,
          checkLoginIframeInterval: 5,
        },
        loadUserProfileAtStartUp: true,
        enableBearerInterceptor: true,
      }).then();
      await this.keycloakService.login({
        redirectUri: window.location.origin + '/home',
      });
    });
  }
}
like image 177
Bassem Salama Avatar answered Nov 21 '25 19:11

Bassem Salama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!