Authenticate your Angular 9 to Azure AD using MSAL

Not so long ago, I wrote an article about using Azure AD authentication from Angular app to Azure functions.
And it looks like Angular 9 broke it.

 

What the heck

 

Angular 9 is a nice upgrade for your web app. But the fact that it breaks the Azure AD might make people stop from upgrading. The purpose of this article is to eliminate this obstacle and allow you to upgrade to Angular 9 with one less problem to worry about.

If you are looking for the previous Angular version setup, check out the Authenticate Angular app to Azure AD section in my previous post.
This post also contains the full solution of how to create your Azure AD app registration and an Azure functions based backed.

You can check the full source code on my GitHub.

 

I assume you have an Angular 9 app

If you are starting fresh, that’s great! Follow the official guide on how to start a new app.

For those of you who want to update to a newer version of Angular, I personally recommend the official handy-dandy update tool.
It allows you to choose the version from which you are updating and provides you with a step-by-step explanation on what to do and which pitfalls to avoid.

 

Configure the parts

Unlike in the previous versions of @azure/msal-angular package, in which the whole configuration was in one single object, the new package (which is required for Angular 9 to work) has everything separated into smaller parts. The rest of the setup stayed the same.

So, for the whole setup, we will be looking into 4 parts.

  1. Setup the packages
  2. MSAL configuration
  3. MSAL configuration – Angular
  4. Module configuration

 

Setup the packages

Following the official npm page, it looks like installing the package is not enough. You also need the MSAL package.

Simply use the following npm command to install everything:

npm install msal @azure/msal-angular --save

This will install all you need and will allow you to progress.

KEEP IN MIND

In the time of writing this article, the @azure/msal-angular package is in beta, so things may have been changed since then.

Now, let’s head to the configuration functions part.

 

MSAL Configuration

We need to create a factory function for the MSAL configuration creation.
Your factory function should look something like that:

function MSALConfigFactory(): Configuration {
  return {
    auth: {
      clientId: environment.aadClientId,
      redirectUri: environment.redirectUrl,
      authority: "https://login.microsoftonline.com/common"
    },
    system: {
      logger: new Logger(loggerCallback)
    }
  }
}

Let’s go over each of the lines:

  • Client Id
    This is the ID of your Azure AD registered app.
  • Redirect Uri
    This is the redirect Uri that is configured in your Azure AD registered app.
  • Authority
    This is the authority that will check your login attempt.
    You can read more on different types of authority in the Msal Client Application Configuration page on Microsoft Docs.

 

MSAL Configuration Angular

This part is specific to configuring the Angular part of the package.

function MSALAngularConfigFactory(): MsalAngularConfiguration {
  return {
    consentScopes: [environment.aadUserReadScope],
    protectedResourceMap: [[environment.apiBaseUrl, [environment.aadUserReadScope]]]
  }
}

Again, let’s go over each of the lines.

  • Consent Scopes
    The scope of your created Azure AD app registration. Use the full URL here.
  • Protected Resource Map
    In this map, we tell Msal which endpoints are protected by which scopes.
    Msal will handle this for us, but we need to define the mapping for it.
    Note that you need only the base URL for the endpoint, not the full URL.

 

Check the npm page for the full list of configuration options

 

Module Configuration

Now we need to configure the module which will glue everything together.

const routes: Routes = [
  { path: "**", component: AppComponent, canActivate: [MsalGuard] }
];

@NgModule({
  declarations: [ ... ],
  imports: [
    ...,
    RouterModule.forRoot(routes),
    MsalModule
  ],
  providers: [
    { 
        provide: HTTP_INTERCEPTORS, 
        useClass: MsalInterceptor, 
        multi: true 
    },
    {
      provide: MSAL_CONFIG,
      useFactory: MSALConfigFactory
    },
    {
      provide: MSAL_CONFIG_ANGULAR,
      useFactory: MSALAngularConfigFactory
    },
    MsalService
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor(msalService: MsalService) {
    msalService.handleRedirectCallback(_ => { });
  }
}

 

Let’s go over the important things.

Lines 2 and 9  
Setup the routes for your app. Use the provided MsalGuard to redirect the user to the login page.

Line 6  
Import the MSAL module

Lines 9-13  
Configure the Msal Http interceptor, which will intercept our Http calls to add the JWT to the authorization header.

Lines 14-21  
Add the configurations with the MSAL consts

Line 22 (Very important)
Due to all the mess that is going on in setting everything up, this line might be forgotten.
Make sure you actually add the MsalService to the providers list.

Lines 27-29
In the configuration we’ve just created, we will have to subscribe to the redirect callback. Even if we don’t do anything there. I hope this will be fixed in some of the versions up ahead.

 

That’s it!

If we didn’t miss anything, we should be able to run the app and it will authenticate to our Azure AD. I tried to make this guide is short to the point as possible.

If you need more explanations and the full solution, including the Azure AD side, please check out my previous post:

Azure AD Authentication from Angular to Azure Functions

Dance

Enjoy your new Angular 9 app with authentication.
Happy coding!

7 thoughts on “Authenticate your Angular 9 to Azure AD using MSAL”

    1. Hi Anupam,
      You will get 401 if something isn’t configured right.
      Please share some more details regarding your configuration so I can help you.

      Also, please double check that you followed all the steps in this guide.

      1. I will share some code and all the details shortly. Thank you so much for reverting to me. I will send you more details, so that you can let me know where am I doing wrong.
        Is there a way to copy paste the images of screenshots ?
        Thank you in advance.

        1. Hi Anupam, I’m glad to help where I can. 🙂
          Feel free to send the details once you have the time.
          Regarding screenshots, sadly, no. This comments system does not allow to attach images to the comments.
          I was planning to upgrade the website for a while now, but I keep delaying it due to time constrains.
          You can upload the image somewhere else and just add a link here in the comment to the image.

  1. Walter Lockhart

    Excellent article Alex. What was the process you used / would recommend to publish / deploy the Angular 9 app to Azure?

    1. Hi Walter, thank you for the appreciation.
      I like the static website option of the Azure Storage Account. I just upload the Angular build result to the relevant blob container and the site is up!

      You can obviously use other methods, like a WebApp that is hosted a service on Azure, but I find the static website option the easiest one.

Leave a Comment

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

Scroll to Top