Using @azure/msal-angular with Sample Application: Various Use Cases with Examples

Authentication and authorization play a crucial role in applications to ensure security and provides a seamless user experience. Microsoft’s Azure Active Directory (Azure AD) is a comprehensive solution which helps to achieve this. In this article, we will discuss how to use the Microsoft Authentication Library for Angular using the @azure/msal-angular to create a sample…

By.

•

min read

Authentication and authorization play a crucial role in applications to ensure security and provides a seamless user experience.

Microsoft’s Azure Active Directory (Azure AD) is a comprehensive solution which helps to achieve this. In this article, we will discuss how to use the Microsoft Authentication Library for Angular using the @azure/msal-angular to create a sample application with examples.

 

We will walk through step by step guide and you will learn the following things while going through the guide:

  • Setting up a new Angular project.
  • Installing the MSAL Angular library and its configuration.
  • Implementation of Authentication.
  • Protecting routes by using MsalGuard.
  • Accessing user information, and accessing protected APIs.
  • Discuss Error Handling.

[lwptoc]

 

Step 1 – Setting up a new Angular project

Create a new Angular project using the following command:

ng new msal-angular-sample.

Replace msal-angular-sample with your desired project name.

 

Change to the project directory

cd msal-angular-sample.

 

Step 2 – Installing the MSAL Angular library

To install the MSAL Angular library, run the following command in your project directory:

npm install @azure/msal-angular@latest @azure/msal-browser@latest

 

Step 3 – Configuring MSAL Angular

Before you can use the MSAL Angular library, you need to register your application in Azure Active Directory. You can follow these steps to register your application:

  1. Sign in to the Azure portal.
  2. Navigate to “Azure Active Directory” > “App registrations” > “New registration”.
  3. Fill in the required details and click “Register”.
  4. Note the “Application (client) ID” and “Directory (tenant) ID” for later use.
  5. Under “Authentication”, add a new redirect URI for your application (e.g., http://localhost:4200).

 

Updating the environment.ts file

Update the src/environments/environment.ts file with the following configuration:

export const environment = {
  production: false,
  msalConfig: {
    auth: {
      clientId: 'YOUR_CLIENT_ID',
      authority: 'https://login.microsoftonline.com/YOUR_TENANT_ID',
      redirectUri: 'http://localhost:4200',
    },
    cache: {
      cacheLocation: 'localStorage',
      storeAuthStateInCookie: false,
    },
  },
};

Replace YOUR_CLIENT_ID and YOUR_TENANT_ID with the values obtained from the Azure portal.

 

You can also have a dynamic redirectUri in your MSAL configuration. Instead of hardcoding the redirectUri value, you can set it based on the current location of your application.

To achieve this, you can use the window.location.origin property which returns the protocol, hostname, and port of the current URL. Update your src/environments/environment.ts file as follows:

export const environment = {
  production: false,
  msalConfig: {
    auth: {
      clientId: 'YOUR_CLIENT_ID',
      authority: 'https://login.microsoftonline.com/YOUR_TENANT_ID',
      redirectUri: window.location.origin,
    },
    cache: {
      cacheLocation: 'localStorage',
      storeAuthStateInCookie: false,
    },
  },
};

 

Step 4 – Implementing authentication

In this step, we will implement the authentication system by creating the Login and Logout components.

 

Adding a login component

Create a new login component using the following command:

ng generate component login

 

In the login.component.ts file, import the MsalService from @azure/msal-angular and update the component to handle user login:

import { Component } from '@angular/core';
import { MsalService } from '@azure/msal-angular';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {

  constructor(private msalService: MsalService) { }

  login(): void {
    this.msalService.loginPopup().subscribe();
  }
}

 

Adding a login button

In the login.component.html file, add a login button that calls the login method when clicked:

<button (click)="login()">Login with Azure AD</button>

 

Adding a logout button

Create a new component for the logout button:

ng generate component logout

 

In the logout.component.ts file, import the MsalService from @azure/msal-angular and update the component to handle user logout:

import { Component } from '@angular/core';
import { MsalService } from '@azure/msal-angular';

@Component({
  selector: 'app-logout',
  templateUrl: './logout.component.html',
  styleUrls: ['./logout.component.css']
})
export class LogoutComponent {

  constructor(private msalService: MsalService) { }

  logout(): void {
    this.msalService.logout();
  }
}

 

In the logout.component.html file, add a logout button that calls the logout method when clicked:

<button (click)="logout()">Logout</button>

 

Step 5 – Protecting routes

To protect routes, import the MsalGuard from @azure/msal-angular and add it as a route guard in your src/app/app-routing.module.ts file:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MsalGuard } from '@azure/msal-angular';

import { LoginComponent } from './login/login.component';
import { ProtectedComponent } from './protected/protected.component';

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'protected', component: ProtectedComponent, canActivate: [MsalGuard] },
  { path: '**', redirectTo: 'login' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

 

Step 6 – Accessing user information

To access user information, we will import the MsalService from @azure/msal-angular in the desired component and call the getAccount() method. For example, in a user profile component:

import { Component } from '@angular/core';
import { MsalService } from '@azure/msal-angular';

@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent {

  constructor(private msalService: MsalService) { }

  getUser(): any {
    return this.msalService.instance.getAccount();
  }
}

 

Step 7 – Accessing protected APIs

Let’s have a look on how to fetch the responses from protected APIs

 

Acquiring an access token

To access protected APIs, you need an access token. In the component that makes API calls, import the MsalService from @azure/msal-angular and call the acquireTokenSilent() or acquireTokenPopup() methods:

import { Component } from "@angular/core";
import { MsalService } from "@azure/msal-angular";

@Component({
  selector: "app-api-call",
  templateUrl: "./api-call.component.html",
  styleUrls: ["./api-call.component.css"],
})
export class ApiCallComponent {
  constructor(private msalService: MsalService) {}

  async getAccessToken(): Promise<string> {
    try {
      const response = await this.msalService
        .acquireTokenSilent({ scopes: ["api://your-api-id/access_as_user"] })
        .toPromise();
      return response.accessToken;
    } catch (error) {
      const response = await this.msalService
        .acquireTokenPopup({ scopes: ["api://your-api-id/access_as_user"] })
        .toPromise();
      return response.accessToken;
    }
  }
}

Replace `api://your-api-id/access_as_user` with the correct scope for your API.

 

Making API calls

Use the acquired access token to make API calls. For example, using the Angular `HttpClient`: `

import { HttpClient, HttpHeaders } from '@angular/common/http';

// ...

constructor(private msalService: MsalService, private httpClient: HttpClient) { }

async callApi(): Promise<any> {
  const token = await this.getAccessToken();
  const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
  return this.httpClient.get('https://your-api-url', { headers }).toPromise();
}

 

Step 8 – Error handling

We can handle errors by subscribing to the msalBroadcastService from @azure/msal-angular and reacting to specific error events. For example, in your app.component.ts file:

import { Component, OnInit } from '@angular/core';
import { MsalBroadcastService, MsalService } from '@azure/msal-angular';
import { EventMessage, EventType } from '@azure/msal-browser';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  constructor(private msalBroadcastService: MsalBroadcastService, private msalService: MsalService) { }

  ngOnInit(): void {
    this.msalBroadcastService.msalSubject$
      .subscribe((event: EventMessage) => {
        if (event.eventType === EventType.LOGIN_FAILURE) {
          // Handle login failure
        } else if (event.eventType === EventType.ACQUIRE_TOKEN_FAILURE) {
          // Handle acquire token failure
        }
      });
  }
}

 

Use cases

Following are a few of the use cases in which @azure/msal-angular library can be utilised in proficient ways:

Single-page application: Integrate MSAL Angular with your Angular single-page application to provide secure authentication and access to protected resources.

Enterprise web app: Use MSAL Angular to authenticate users in an enterprise web app and access resources in a secure manner.

Mobile app: Incorporate MSAL Angular into your Angular-based mobile app to allow users to authenticate with their Azure AD credentials and access protected APIs.

 

Conclusion

In this article, we covered how to use the @azure/msal-angular library to implement authentication and authorization in an Angular application, including various use cases and examples.

This powerful library simplifies the integration of Azure Active Directory, enabling you to create secure, user-friendly applications.

Leave a Reply

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