Angular4 azure active directory authentication using ng2-adal library removes id_token from the url.
I referred the following blog for the implementation. https://dotronald.be/add-azure-active-directory-to-an-existing-angular-2-single-page-application/
Installed ng4-adal
Created a typescript config file for ng4-adal to set azure connection details as follows, import {Injectable} from '@angular/core';
@Injectable() export class AdalConfig { public get getAdalConfig(): any { return { tenant: 'YOUR TENANT NAME', clientId: 'YOUR CLIENT ID', redirectUri: window.location.origin + '/', postLogoutRedirectUri: window.location.origin + '/logout' }; } }
Created a canActivate guard that authenticates the angular routes before navigation as follows,
import { Injectable } from '@angular/core'; import { Router, CanActivate, ActivatedRouteSnapshot,RouterStateSnapshot, NavigationExtras } from '@angular/router'; import {AdalService} from "ng4-adal/core"; @Injectable() export class AuthenticationGuard implements CanActivate { constructor(private _adalService: AdalService, private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean{ if (this._adalService.userInfo.isAuthenticated) { return true; } else { this._adalService.login(); return false; } } }
Added the following code in the constructor of the app.component.ts to initiate the ng4-adal service as follows,
constructor( private _adalService: AdalService, private _adalConfigService: AdalConfig ) {this._adalService.init(this._adalConfigService.getAdalConfig);}
To prevent the user having to log in every time again, the authentication token is stored in the browser cache. This allows us to try to retrieve this token and continue using the application without being redirected again to the Azure login page.
Added the following code in the ngOninit of the app.component.ts to overcome the above issue as follows,
ngOnInit() {
this._adalService.handleWindowCallback();
this._adalService.getUser();
}
Set the guard created in step 3 for required routes in the app-routing.ts file as follows,
const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full', canActivate: [AuthenticationGuard]}, { path: 'admin-measure', redirectTo: '/#admin-measure'}, { path: 'home', component: HomeComponent, canActivate: [AuthenticationGuard] }, { path: 'logout', component: LogoutComponent }, { path: 'unauthorized', component: UnauthorizedComponent } ];
Registered the services in app.module.
The error i'm getting in console follows, ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'id_token'
Problem found by research: There's an issue with redirects when using hashes in Angular 2. The problem is that when the authResult comes back in the redirect after authentication, Angular thinks it's a route called access_token.
Any solution for this?