Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 + Keycloak allow anonymous users

I am trying to allow anonymous users to my app and I am using this library: 'keycloak-angular' with Angular 5. In the description it requires me to initialize the app like so:

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

export function keycloakInitializer(keycloak: KeycloakService): () => Promise<any> {
return (): Promise<any> => {
    return new Promise(async (resolve, reject) => {
        try {
            await keycloak.init({
                config: {
                    url: 'my-url',
                    realm: 'my-realm',
                    clientId: 'my-client-id'
                },
                initOptions: {
                    onLoad: 'check-sso',
                    checkLoginIframe: false
                }
            });
            resolve();
        } catch (error) {
            reject(error);
        }
    });
};

Doing so it automatically triggers a login prompt to the keycloak server. Is there any way to trigger login only on demand?

Thank you

like image 386
KangJiYoung13 Avatar asked Jun 06 '26 08:06

KangJiYoung13


1 Answers

Yes, this can be done. When you use a factory provider, angular invokes the factory when it resolves the dependency.

To defer the prompt, wrap the function in a factory function that returns the original and provide that.

Here is what that looks like

export async function initializeApp(
  keycloak: KeycloakService,
  deferredInitializer: typeof keycloakInitializer
) {
  if (someCondition) {
    const initializer = await deferredInitializer(keycloak);

  }
}
export async function keycloakInitializer(keycloak: KeycloakService) {
  await keycloak.init({
    config: {
      url: 'my-url',
      realm: 'my-realm',
      clientId: 'my-client-id'
    },
    initOptions: {
      onLoad: 'check-sso',
      checkLoginIframe: false
    }
  });
}

const providers = [
  {
    provide: APP_INITIALIZER,
    useFactory: initializeApp,
    deps: [KeycloakService, keycloakInitializer]
  }
];

The actual keycloakInitializer function is very poorly written so I am going to refactor it for posterity.

export async function keycloakInitializer(keycloak: KeycloakService) {
  await keycloak.init({
    config: {
      url: 'my-url',
      realm: 'my-realm',
      clientId: 'my-client-id'
    },
    initOptions: {
      onLoad: 'check-sso',
      checkLoginIframe: false
    }
  });
}
like image 116
Aluan Haddad Avatar answered Jun 08 '26 22:06

Aluan Haddad



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!