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
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
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With