Your Vision Our Goal
+91 8888860970 info@upstacksolutions.com

ADAL Angular integration

In this blog we are covering angular app setup and configuring it to use azure active directory authentication. First we will register app in Azure Active directory.

Open the azure portal and search for azure active directory

Azure portal

Select Azure Active Directory and click on App registration. It will display registered apps.

Azure portal: Active Directory App listing

Register new app by clicking on new registration. It will open the below screen, provide basic app details and register the app.

Note: provide redirect URI, it will return the authentication response to that URI after successfully authenticating the user. You can change redirect uri after app registration also.

Azure portal: App registration screen

After app registration you will get client & tenant id which we need for angular application. Here we are done with ADAL setup.

Azure portal: App details

Angular Setup: Follow the steps to create angular application.

ng new adal-angular

Install microsoft-adal-angular6 library which helps you to integrate your web app with Microsoft’s AAD.

npm i microsoft-adal-angular6

Create adal-config.ts file and add below code.

export function getAdalConfig() {
    return {
        tenant: '{tenant_id}',
        clientId: '{client_id}',
        redirectUri: window.location.origin,
        endpoints: { 
          "https://localhost/Api/": "4200",
        },
        navigateToLoginRequestUrl: false,
        cacheLocation: 'localStorage'        
      };
  }

Edit app.module.ts and import MsAdalAngular6Module.forRoot(getAdalConfig)

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { appRoutes } from './app-routing.module';
import { Routes, RouterModule } from '@angular/router';

import { MatCardModule } from '@angular/material/card';
import { MatButtonModule} from '@angular/material/button';
import { MatMenuModule } from '@angular/material/menu';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatIconModule } from '@angular/material/icon';
import { SuccessComponent } from './success/success.component';
import { AccessDeniedComponent } from './access-denied/access-denied.component';

import { getAdalConfig } from './adal-config';
import { MsAdalAngular6Module } from 'microsoft-adal-angular6';
import { AuthenticationGuard } from 'microsoft-adal-angular6';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth.interceptor';
import { AuthGuard } from './auth.guard';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    SuccessComponent,
    AccessDeniedComponent,    
  ],
  imports: [
    MsAdalAngular6Module.forRoot(getAdalConfig),
    BrowserModule,
    MatButtonModule,
    MatCardModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    RouterModule.forRoot(appRoutes)

  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    },
     AuthenticationGuard,
     AuthGuard
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Open app-routing.module.ts and attach AuthenticationGuard

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AppComponent } from './app.component';

import { SuccessComponent } from './success/success.component';
import { AccessDeniedComponent } from './access-denied/access-denied.component';

import { AuthenticationGuard } from 'microsoft-adal-angular6';

import { AuthGuard } from './auth.guard';

export const appRoutes: Routes = [
  {
    path: '',
    redirectTo: 'success',
    pathMatch: 'full'
  },
  { path: 'success',
  component: SuccessComponent,
  canActivate: [AuthGuard],
  canActivateChild: [AuthenticationGuard],
  children: [
    {
      path: '',
      redirectTo: 'default',
      pathMatch: 'full',
    },
  ]},
  { path: 'access-denied', component: AccessDeniedComponent }
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ],
  exports: [
    RouterModule
]
})
export class AppRoutingModule { }

After all these configuration you can run the angular application by ng serve. It will open default url http://localhost:4200 and redirect to ADAL login page.

ng serve
Adal login page

After successful login you will redirect to homepage with token

Create auth.service.ts file to access adal properties

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { MsAdalAngular6Service } from 'microsoft-adal-angular6';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(
    private adalSvc: MsAdalAngular6Service,
    private router: Router
  ) { 
  }
  

  logout(){
    this.adalSvc.logout() 
    localStorage.clear();
    this.router.navigate(['/']).then(nav => {
      // console.log(nav); 
    }, err => {
      // console.log(err) 
    });
  }

  getToken(){
   return this.adalSvc.accessToken;  
  }

  // get user details
  getLoggedInUser(): any {  
    return this.adalSvc.LoggedInUserName;  
  } 

   // get user details
   getLoggedInUserInfo(): any {  
    return this.adalSvc.userInfo;  
  } 
}

I hope I helped you to understand how to implement Azure Active Directory authentication. If you have any question leave me a comment under this post.

Leave a Reply

Your email address will not be published. Required fields are marked *