I have been integrating keycloak-js and angular to achieve the following scenario in a multitenant application:
- The
/signingpage is public (WithoutGuardrules) and displays aformwere the user manually type theKeycloak Realm, like the following example:
When he clicks the button confirm, the component stores the
Realmin theSessionStorageand calls a serviceSecurityServiceto manage the login using the methodsignInThe user is redirected to the
KeycloakLoginpage to input the credentials, then is redirected to the/homepage of the application.Everything works fine but I want to know if it is possible to initialize and update the value of the
keycloakproperty in theSecurityServicewithout the need of the methodinitevery time I want to use it, because it is defined empty by defaultkeycloak: Keycloak = new Keycloak();I need to executethis.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;
}
}
