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.
Very Good!
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.
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.
Super simple and perfectly explained tutorial. Thanks.
Can anyone share the React & Microsoft Login (Using MSAL)
Superb
Unable to perform routing after logging in and even on reload, it asks to sign in again, could you please help ? It's urgent.
thank you so much. Nice explanation
Many many thanks for awesome video! Very clear and full of knowledge
Thank you, very usefull!!!
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!
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.
Thanks!
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
Hi Genka, Thanks for such a quality video, how do we configure multi-tenant in msal using factory method
Hello
Is it free of cost to create an account on azure and use it?
Does msal.logout(), will clear local storage?
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.
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
Thanks crack, great video, this is very helpful for a current project, greetings from Medellin – Colombia