I'm trying to integrate with an identity provider (Keycloak in my case) in my Angular project. I'm using "angular-oauth2-oidc" library for that purpose.
I'm able to redirect a user from my "home" page to the "login" page of Keycloak on a button click, and normally, I would redirect the user to the "landing" page of my application after successful login. However, when I do that, I realized the access token is not yet set to my browser storage when Keycloak redirects the user to the "landing" page. So instead, I had to redirect the user back to "home" page instead, and then to the "landing" page, so that in the mean time tokens are set to storage.
Obviously, this is not a good practice and I believe I'm doing something wrong there. Here are the codes that I've been working on;
home.component.html
<button class="btn btn-default" (click)="login()">
Login
</button>
home.component.ts
login(): void {
this.authService.login();
}
auth.service.ts
@Injectable({ providedIn: 'root' })
export class AuthService {
constructor(private oauthService: OAuthService, private router: Router) {
this.configure();
}
authConfig: AuthConfig = {
issuer: ...
redirectUri: window.location.origin + '/home',
clientId: ...
scope: ...
responseType: 'code',
disableAtHashCheck: true
}
login(): {
this.oauthService.initCodeFlow();
}
private configure() {
this.oauthService.configure(this.authConfig);
this.oauthService.tokenValidationHandler = new JwksValidationHandler();
this.oauthService.loadDiscoveryDocumentAndTryLogin().then(() => {
if(this.hasValidToken()){
this.oauthService.setupAutomaticSilentRefresh();
this.router.navigateByUrl('/landing');
}
});
}
}
What I want to do instead would be something like this;
auth.service.ts.
@Injectable({ providedIn: 'root' })
export class AuthService {
constructor(private oauthService: OAuthService, private router: Router) {
this.configure();
}
authConfig: AuthConfig = {
issuer: ...
redirectUri: window.location.origin + '/landing',
clientId: ...
scope: ...
responseType: 'code',
disableAtHashCheck: true
}
login(): {
this.oauthService.initCodeFlow();
}
private configure() {
this.oauthService.configure(this.authConfig);
this.oauthService.tokenValidationHandler = new JwksValidationHandler();
this.oauthService.loadDiscoveryDocumentAndTryLogin().then(() => {
if(this.hasValidToken()){
this.oauthService.setupAutomaticSilentRefresh();
}
});
}
}
Any help would be appreciated.