Microsoft Authentication Library for JavaScript (MSAL.js) - Gary-Moore/developmentwiki GitHub Wiki

MSAL.js

The MSAL library for JavaScript enables client-side JavaScript web applications, running in a web browser, to authenticate users using Azure AD work and school accounts (AAD), Microsoft personal accounts (MSA) and social identity providers like Facebook, Google, LinkedIn, Microsoft accounts, etc. through Azure AD B2C service. It also enables your app to get tokens to access Microsoft Cloud services such as Microsoft Graph.

msal.js github

getting started

Angular MSAL library

Install npm

npm install msal

Install angular msal package

npm install @azure/msal-angular --save

Include and initialize the MSAL module in your app module.

@NgModule({
  imports: [ MsalModule.forRoot({
                    clientID: "Your client ID"
                })]
         })

  export class AppModule { }

Config options for MSAL initialization

Besides the required clientID, you can optionally pass the following config options to MSAL module during initialization. For example:

@NgModule({
  imports: [ MsalModule.forRoot({
                  clientID: "Your client ID",
                  authority: "https://login.microsoftonline.com/contoso.onmicrosoft.com/",
                  redirectUri: "http://localhost:4200/",
                  validateAuthority : true,
                  cacheLocation : "localStorage",
                  postLogoutRedirectUri: "http://localhost:4200/",
                  navigateToLoginRequestUrl : true,
                  popUp: true,
                  consentScopes: ["user.read", "api://a88bb933-319c-41b5-9f04-eff36d985612/access_as_user"],
                  unprotectedResources: ["https://angularjs.org/"],
                  protectedResourceMap : protectedResourceMap,
                  logger :loggerCallback,
                  correlationId: '1234',
                  level: LogLevel.Verbose,
                  piiLoggingEnabled: true,
                })]
           })

  export class AppModule { }

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: 'product', component: ProductComponent, canActivate : [MsalGuard],
    children: [
      { path: 'detail/:id', component: ProductDetailComponent  }
    ]
   },
  { path: 'myProfile' ,component: MsGraphComponent, canActivate : [MsalGuard] },

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: [ ProductService, {
        provide: HTTP_INTERCEPTORS,
        useClass: MsalInterceptor,
        multi: true
    }
   ],