Accessing keycloak functions with keycloak-angular

1.4k Views Asked by At

In my Angular app I am initializing on load keycloak this way:

app.module.ts:

providers: [
    { 
      provide: APP_INITIALIZER, 
      useFactory: initializer, 
      deps: [ KeycloakService, AppService ], 
      multi: true
    }
  ],

in app-init.ts:

import { KeycloakService } from 'keycloak-angular';
import { AppService } from 'src/app/app.service';
import { environment } from '../environments/environment';
 
export function initializer(keycloak: KeycloakService, appService: AppService): () => Promise<any> {
    return (): Promise<any> => {
        return new Promise<void>(async (resolve, reject) => {
          try {
            await keycloak.init({
                config: {
                    url: environment.keycloak.issuer,
                    realm: environment.keycloak.realm,
                    clientId: environment.keycloak.clientId
                },
              loadUserProfileAtStartUp: true,
              initOptions: {
                onLoad: 'check-sso',
                checkLoginIframe: true,
                pkceMethod: 'S256'
              },
              bearerExcludedUrls: ['/']
            }).then(async a => {
              appService.setLoggedIn(a);  // passing authorization status: true or false to appservice for later use
            });
            resolve();
          } catch (error) {
            reject(error);
          }
        })
      };
}

Keycloak-js has a lot of functionality: (https://www.keycloak.org/docs/latest/securing_apps/). For example how can I use this method: createLogoutUrl(options).

When I try doing keycloak.createLogoutUrl() it says that keycloak (which is KeycloakService from keycloak-angular) does not have this functionality.

How can I access this extra functionality from my keycloak instance?

1

There are 1 best solutions below

0
On

I found the solution. keycloka-angular has method getKeycloakInstance()., which is not mentioned in documentation, but I found it examples.

let keycloakInstance = keycloak.getKeycloakInstance();

Now, my property keycloakInstance has access to all keycloak-js properties and methods.