I’m working on angular-oauth2-oidc and keycloak. I can login (redirecting to keycloak login page), and session has created inside keycloak for loggedin user.
However, oauthService.getIdentityClaims() returns null so I can’t get the username from this:
Below is my code:
environment.ts
export const environment = {
production: false,
envName: 'local',
keycloak:{
issuer:"http://localhost:8080/auth/realms/MySSOApp",
redirectUri:"http://localhost:4202/",
clientId:"sso-app3-client",
scope:"openid profile email"
}
};
sso-config.ts
import { AuthConfig } from 'angular-oauth2-oidc';
import { environment } from 'src/environments/environment';
export const authCodeFlowConfig: AuthConfig = {
// Url of the Identity Provider
issuer: environment.keycloak.issuer,
redirectUri: environment.keycloak.redirectUri,
clientId: environment.keycloak.clientId,
// dummyClientSecret: 'secret',
responseType: 'code',
scope: environment.keycloak.scope,
requireHttps: false,
showDebugInformation: true,
disableAtHashCheck: true,
strictDiscoveryDocumentValidation: false
};
export class OAuthModuleConfig {
resourceServer: OAuthResourceServerConfig = {sendAccessToken: false};
}
export class OAuthResourceServerConfig {
allowedUrls?: Array<string>;
sendAccessToken = true;
customUrlValidation?: (url: string) => boolean;
}
app.component.ts
import { Component, ViewChild } from '@angular/core';
import { OAuthService, NullValidationHandler } from 'angular-oauth2-oidc';
import { authCodeFlowConfig } from 'src/app/sso-config';
import { filter } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'sso-app';
name: string = "";
private _decodedAccessToken: any;
private _decodedIDToken: any;
get decodedAccessToken() { return this._decodedAccessToken; }
get decodedIDToken() { return this._decodedIDToken; }
@ViewChild('yourChild' /* #name or Type*/, {static: false}) child: any;
constructor(private oauthService: OAuthService) {
}
ngOnInit() {
//this.initAuth();
}
async initAuth(): Promise<any> {
return new Promise<void>((resolveFn, rejectFn) => {
// setup oauthService
this.oauthService.configure(authCodeFlowConfig);
this.oauthService.setStorage(localStorage);
this.oauthService.tokenValidationHandler = new NullValidationHandler();
// subscribe to token events
this.oauthService.events.pipe(filter((e: any) => {
console.log("e : ", e);
return e.type === 'token_received';
})).subscribe(() => {
console.log("here..");
this.handleNewToken();
});
this.oauthService.loadDiscoveryDocumentAndLogin().then(isLoggedIn => {
console.log("isLoggedIn: ", isLoggedIn);
if (isLoggedIn) {
this.oauthService.setupAutomaticSilentRefresh();
resolveFn();
} else {
this.oauthService.initImplicitFlow();
rejectFn();
}
});
});
}
private handleNewToken() {
this._decodedAccessToken = this.oauthService.getAccessToken();
this._decodedIDToken = this.oauthService.getIdToken();
}
}
navbar.component.ts
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { OAuthService } from 'angular-oauth2-oidc';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
name: string = "";
constructor(private oauthService: OAuthService) { }
@Output() someEvent = new EventEmitter<any>();
givenName:any;
ngOnInit(): void {
const userClaims: any = this.oauthService.getIdentityClaims();
console.log(userClaims);
if(userClaims){
this.givenName = userClaims.name ? userClaims.name : "";
}
}
login() {
this.someEvent.next('somePhone');
}
logout() {
this.oauthService.logOut();
}
// get givenName() {
// const claims: any = this.oauthService.getIdentityClaims();
// console.log("Claims ======>>>>>>", claims);
// if (!claims) {
// return null;
// }
// return claims['name'];
// }
}
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './components/navbar/navbar.component';
import { HomeComponent } from './components/home/home.component';
import { WelcomeComponent } from './components/welcome/welcome.component';
import { Routes, RouterModule, Router } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { AuthConfig, OAuthModule, OAuthService, OAuthStorage } from 'angular-oauth2-oidc';
import { AuthGuard } from './auth.guard';
import { authCodeFlowConfig, OAuthModuleConfig } from './sso-config';
const routes: Routes = [
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'welcome', component: WelcomeComponent },
{ path: '', redirectTo: '/welcome', pathMatch: 'full' }, // anything that didn't match above routes then redirect to products
{ path: '**', redirectTo: '/welcome', pathMatch: 'full' }, // anything that didn't match above routes then redirect to products
];
@NgModule({
declarations: [
AppComponent,
NavbarComponent,
HomeComponent,
WelcomeComponent
],
imports: [
RouterModule.forRoot(routes),
BrowserModule,
AppRoutingModule,
HttpClientModule,
BrowserAnimationsModule,
OAuthModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
auth.guard.ts
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { OAuthService } from 'angular-oauth2-oidc';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private oauthService: OAuthService, private router: Router) {
}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
var hasIdToken = this.oauthService.hasValidIdToken();
var hasAccessToken = this.oauthService.hasValidAccessToken();
console.log("==", hasIdToken);
console.log("==", hasAccessToken);
if ((hasAccessToken)) {
return true;
}
this.router.navigate(["/welcome"]);
return false;
}
}
Any idea what I needs to be done here to work it properly.
Thanks