Microsoft Authentication Library for Angular - V 2
The MSAL library preview for Angular is a wrapper of the core MSAL.js library which enables Angular applications to authenticate enterprise users using Microsoft Azure Active Directory (AAD), Microsoft account users (MSA), users get access to Microsoft Cloud OR Microsoft Graph.
Installation
The msal-angular package is available on NPM:
npm install @azure/msal-angular --save
Usage
Prerequisite
Before using MSAL, register your application in Azure AD v2.0 portal to get your clientID.
1. Include and initialize the MSAL module in your app module.
Import MsalModule into app.module.ts
. To initialize MSAL module you are required to pass the clientID of your application which you can get from the application registration.
@NgModule({
imports: [ MsalModule.forRoot({
clientID: "Your client ID",
authority: "https://login.microsoftonline.com/contoso.onmicrosoft.com/",
redirectUri: "http://localhost:4200/",
cacheLocation : "localStorage",
consentScopes: ['openid']
})]
})
export class AppModule { }
- authority : A URL indicating a directory that MSAL can use to obtain tokens.
- redirectUri : The redirect URI of your app, where authentication responses can be sent and received by your app. It must exactly match one of the redirect URIs you registered in the portal, except that it must be URL encoded. Defaults to window.location.href.
- cacheLocation : Sets browser storage to either 'localStorage' or sessionStorage'. Defaults is 'sessionStorage'.
- consentScopes : Allows the client to express the desired scopes that should be consented. Scopes can be from multiple resources/endpoints. Passing scope here will only consent it and no access token will be acquired till the time client actually calls the API. This is optional if you are using MSAL for only login(Authentication).
2. Secure the routes in your application
You can add authentication to secure specific routes in your application by just adding canActivate : [MsalGuard]
to your route definition. It can be added at the parent or child routes.
{ path: 'home', component: HomeComponent, canActivate: [MsalGuard] },
{ path: '', redirectTo: 'home', pathMatch: 'full' }
When user visits the home route, the library prompts the user to authenticate.
3. Get tokens for Web API calls
MSAL Angular allows you to add an Http interceptor (MsalInterceptor)
in your app.module.ts as follows. MsalInterceptor will obtain tokens and add them to all your Http requests in API calls except the API endpoints listed as unprotectedResources.
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
}
],
Using MsalInterceptor is optional and you can write your own interceptor if you choose to. Alternatively, you can also explicitly acquire tokens using the acquireToken.