,

Using Microsoft Authentication Library (MSAL) for Angular and Microsoft Login

Posted by


Angular & Microsoft Login – Using Microsoft Authentication Library (MSAL)

Microsoft Authentication Library (MSAL) is a powerful library that provides the capability to integrate Microsoft login into Angular applications. With MSAL, developers can easily implement secure authentication using Microsoft accounts and access various Microsoft services and APIs.

Setting up MSAL in Angular

The first step is to install the MSAL library in your Angular project. Open a terminal and navigate to the root folder of your project. Run the following command to install MSAL:

npm install @azure/msal-angular

Once the installation is complete, you need to configure MSAL in your Angular application. Open the app.module.ts file and import the required modules:

import { MsalModule, MsalInterceptor } from '@azure/msal-angular';

After importing the modules, add the following code to the imports array:

MsalModule.forRoot({
auth: {
clientId: 'YOUR_CLIENT_ID',
authority: 'https://login.microsoftonline.com/YOUR_TENANT_ID',
redirectUri: 'http://localhost:4200',
},
cache: {
cacheLocation: 'localStorage',
storeAuthStateInCookie: false,
},
})

Make sure to replace YOUR_CLIENT_ID with your actual client ID and YOUR_TENANT_ID with your tenant ID. The authority parameter should be set to the Microsoft Azure AD authority URL.

Adding Microsoft Login Button

To add a Microsoft login button to your Angular application, create a component and add the following HTML code:

<button (click)="login()">Microsoft Login</button>

In the component’s TypeScript file, import the AuthService from the MSAL library and inject it into the constructor:

import { AuthService } from '@azure/msal-angular';

Then, add the following code to the component’s class:

constructor(private authService: AuthService) {}

login() {
this.authService.loginPopup().subscribe((response) => {
// Handle the response after successful login
});
}

The login() function triggers the Microsoft login popup. It returns an Observable that you can subscribe to and handle the response after a successful login.

Accessing Microsoft Services and APIs

Once the user is logged in, you can use MSAL to access various Microsoft services and APIs. MSAL provides methods to acquire access tokens for different resources. For example, to access the Microsoft Graph API, you can use the following code:

this.authService.acquireTokenSilent({ scopes: ['https://graph.microsoft.com/.default'] }).subscribe((tokenResponse) => {
// Use the access token to make API requests
// For example, call the Microsoft Graph API
this.http.get('https://graph.microsoft.com/v1.0/me', {
headers: {
Authorization: 'Bearer ' + tokenResponse.accessToken
}
}).subscribe((response) => {
// Handle the API response
});
});

The acquireTokenSilent() method is used to acquire an access token silently without showing any prompts to the user. The scopes parameter determines the resources and permissions required by your application.

Conclusion

By integrating MSAL into your Angular application, you can easily implement secure Microsoft login and access various Microsoft services and APIs. With MSAL, authentication becomes a breeze, and you can focus on building your application’s core functionality.

0 0 votes
Article Rating
20 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
lestgotrader
1 year ago

Very Good!

Kole
1 year ago

Very well done. Now if I can implement it as easy as you show. I'd like to know how Guard can force a redirect if a user tries to access the restricted page.

VeeraRaghava Gupta
1 year ago

Hi Genka, We have requirement to store MSAL acquired token in cache and it should clear automatically on closing all browser windows and also token should share between windows and tabs.

Can you please shed some light on the approach to be taken.

Neeraj K.
1 year ago

Super simple and perfectly explained tutorial. Thanks.

Sana R
1 year ago

Can anyone share the React & Microsoft Login (Using MSAL)

Chandrashaker Kadavergula
1 year ago

Superb

Binny Chopra
1 year ago

Unable to perform routing after logging in and even on reload, it asks to sign in again, could you please help ? It's urgent.

Suresh Kb
1 year ago

thank you so much. Nice explanation

Radek Fluder
1 year ago

Many many thanks for awesome video! Very clear and full of knowledge

SiiN. Sistema de control de Inventarios
1 year ago

Thank you, very usefull!!!

Ganeshraj K
1 year ago

Hi Genka, I'm getting this exception Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[MsalGuard -> InjectionToken MSAL_GUARD_CONFIG -> InjectionToken MSAL_GUARD_CONFIG -> InjectionToken MSAL_GUARD_CONFIG]:
NullInjectorError: No provider for InjectionToken MSAL_GUARD_CONFIG!

Lyubomyr Plakhotnyuk
1 year ago

What if I have not a Single page application URIs, but Web, any differences/additions to be done ? I receive an error : Cross-origin token redemption is permitted only for the 'Single-Page Application' client-type.

desarrollador dev
1 year ago

Thanks!

Avanish Kumar
1 year ago

Wow, you explained it very well. a big thanks to u for explaining msal config. yesterdayi watched a tutorial video on msal cant get it but today you teached it very well. tysm

Shashi Kant
1 year ago

Hi Genka, Thanks for such a quality video, how do we configure multi-tenant in msal using factory method

Anand Chavan
1 year ago

Hello
Is it free of cost to create an account on azure and use it?

shree susma
1 year ago

Does msal.logout(), will clear local storage?

vivek kalia
1 year ago

I have suffer from one issue with redirect login I have two outside page forgot-password and reset-password so that,s why I have load login page on empty route . beacause user have to access to come back login page from this outside page. but the problem is that when i click on login button after enter the credentials route firstly come to empty route that is login page and after login , login page is visible for one second and then user redirect to home page. beacuse the getAllaccounts give the response after some time and isLoggedin () not give true response immedatialy. so thats why login page comes in screen for few second after login.

nolimitsREAL
1 year ago

One thing I need to know, how I communicate with my API and verify through my API that the user that signed in is the respective person, so that he can access to different things ? thank you, I hope it makes sense

DacarSoft
1 year ago

Thanks crack, great video, this is very helpful for a current project, greetings from Medellin – Colombia