You are currently viewing Setup Azure AD OAuth with Angular Application

Setup Azure AD OAuth with Angular Application

Now a days, many people are preferring Angular to go for fairly large scale and complex applications. In this article, we will have a look at how to enable OAuth 2.0 in a single page application which was created using Angular framework.

Please note that you will need Azure subscription to follow the steps in the article. If you don’t have an Azure subscription, create a free account before you begin.

What is Azure Active Directory ?

Azure Active Directory is a cloud based identity and access management (aka IAM) service which is provided by Microsoft Azure.

It comes in two flavours on high level, Azure AD B2B and Azure AD B2C.

Azure AD B2B is for businesses that want to securely share files and resources with external users so they can collaborate.  Azure AD B2C is primarily for businesses and developers that create customer-facing apps. Please refer this article for detailed comparison.

As far as pricing is concerned, Azure AD has 3 main pricing tiers, Free, Azure AD P1 and Azure AD P2. Refer this page for detailed comparison of pricing tiers.

Now, why you should use Azure AD ?

In my opinion, there are two important reasons why you should go for Azure AD.

Firstly, the most important reason why I would go for Azure AD is “why to reinvent the wheel?” when you can easily integrate with always available, pluggable service.

Azure AD provides you effective and efficient way to manage the identities and access of the users. In Azure portal, you can either create user objects, change their access levels and even disable them.

Microsoft invests a lot of money annually to make sure that the identity and access management solutions provided by Microsoft is up to date and secure. The teams at Microsoft are making sure that Azure AD is secure enough to safeguard your data and application.

You can also write your own authentication service, but you will always need to be updated with latest trends in security and make sure that your custom implementation is up to date. This is very tedious job, if not impossible. Azure AD is a way through which you can keep yourself completely focused on application’s business functionality.

ADAL vs MSAL ?

Before looking at actual steps to configure Azure AD with Angular application, let’s have a look at what options we have at our hand.

There are two libraries which are provided by Microsoft:

  • ADAL – Azure AD Authentication Library
  • MSAL – Microsoft Authentication Library

There are a lot of technical differences between the two libraries. One of the major difference is ADAL uses OAuth 1.0. MSAL uses OAuth 2.0 protocol and it is now the recommended auth library to integrate with Microsoft identity platform.

If you are curious to know other technical differences, you can refer this documentation for more details.

Create Angular App

Run below commands from Azure CLI to create the new Angular application. Once the application is created, try to run it and you will see a default home page at http://localhost:4200

If you are new to Angular world, refer my previous blog article to create your first Angular app.

## Install Angular CLI
npm install -g @angular/cli

## To Create New Angular Application 
ng new SecureApp

## Go to Directory Containing Angular App
CD SecureApp

## Create home component 
## copy everything from app component to home 
ng g component home

## To Run The Newly Created App
ng serve

We will create a home component in below script. Then copy all the html from app.component.html to home.component.html. In home.component.ts, add a property with name title.

Then you can create a simple route with empty prefix and redirect user to home component. The routing module configurations should be as shown below:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MsalGuard } from '@azure/msal-angular';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {
    path: '',
    pathMatch: 'prefix', 
    component: HomeComponent,  
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Register in Azure AD

Now, when an Angular application runs, by default it runs on http://localhost:4200.

Next step now is to configure your application in Azure AD.

Login to Azure Portal to your Azure subscription. Go to Azure Active Directory option shown on the left navigation. Then select the App Registrations option.

  • Name: Some name for your app registration
  • Redirect URI: the default application URI, for our case add the default application URIL as shown in snapshot.

Keep rest of the inputs to their default values and then click on Register button.

This will create a new App registration.

Now you select the SecureApp registration, then a new panel will open. There, select Authentication option from left side pane. On the new panel, make sure that Access Tokens and ID Tokens checkboxes are checked there. If not, check them and then click on save.

Install MSAL

Now, lets move to our angular application. Install the MSAL packages using below command. The below command will install two packages – MSAL and MSAL-Angular.

## Install MSAL package
npm install msal 

## and MSAL Angular package
npm install @azure/msal-angular             

Angular App Module

Once two packages are installed, next thing is to setup connection between Azure Active Directory and your Angular app.

In your app module(i.e. app.module.ts), import the MsalModule as shown in below snippet.

The above snippet uses GUIDs which can be found in your Azure Portal. Go to Azure Active Directory App registrations and open SecureApp.

You will see the client ID (yellow colored) and tenant ID (green colored) shown in below snapshot.

Angular Routing

Once the MsalModule is imported, you need to ensure that you guard the routes in your application using MsalGuard as shown in below code snippet.

This SecureApp is just a simple app with only one route. But if you have complex app with lazy loading and multiple child routes, then you should configure the MsalGuard for all those child routing modules. If you forget to add Guard for any of the routes and if user has bookmarked that URL, the application routing will allow user to anonymously access that URL.

Login and Logout

Now let’s create a new service using “ng g service Auth” command. Then add below code in the auth.service.ts.

Then go to app.component.ts and make sure the code looks as shown in below code snippet.

Also to test logout, add below button in app.component.html. This we are adding below router outlet, it will trigger the logout function.

Run and Verify

Now when you run the application again after performing above steps, you will be redirected to the login page. This login page is provided by Azure.

NOTE: If you use Azure AD B2C, you can also customize the look and feel of the login page to match its design with your application.  

We have seen how easy it is to enable the authentication using Azure Active Directory. I hope this article helps you.

Leave a Reply

This Post Has 4 Comments

  1. Diego Peppert

    Hi, thanks for this extreme helpful tutorial. Do you know how can i add custom claims to msal? I want to enable and disable a button using that custom claim. Otherwise, do you know any other solution? Thanks in advance!

    1. Manoj Choudhari
      Manoj Choudhari

      I currently do not have any solution. I can try some experiments in next few weeks and this can be good topic for my next post. Thanks !

  2. Mamta

    Hi Manoj,

    I want to achieve the same purpose like yours but instead of redirecting users to the login microsoft’s page I want to redirect it to my /login page which is custom designed.
    If the user is authenticated, then redirect to /search page.
    If not authenticated, then redirect to /login page and show the custom sign in button I have designed for azure.

    Currently adding MSALGUARD blocks my login page but serves the purpose. I want to serve the same purpose as well as have my custom login page instead of the login.microsoft page.

    Could you please help me out?

    1. Manoj Choudhari
      Manoj Choudhari

      There are ample of configurations (like inserting your brand image or changing background) which can help you to change the default look-and-feel of the page. The customization options are discussed in the blog past – https://manojchoudhari.wordpress.com/2020/05/24/login-page-customization-options-in-azure-ad-b2c/

      Even then, if you want your own login page, you can host a website (or use Azure storage to host static website). Then configure Azure AD to redirect login requests to this new site. I will try to cover this in my upcoming post. Hope this helps.