ASP.NET Core: How to implement Azure Active Directory (AAD) Authentication in ASP.NET Core

In this tutorial, we will implement security for ASP.NET Core Application using Azure Active Directory (AAD).  Recently, when I was discussing with my students regarding ASP.NET Core security, one of students have asked me a question regarding an integration of Azure Active Directory (AAD) users with ASP.NET Core apps. After showing the implementation to my students, I thought to publish a simple tutorial on this. In this tutorial, I will cover some topics as prerequisites to understand the ASP.NET Core security using AAD.

Microsoft Identity Platform

Microsoft Identity Platform provides facility to design an application that provides an access of the application to users using their Microsoft Identities and Social Accounts. If you are deploying the application on Microsoft Azure then implementing security using this platform reduces an additional need of the code to manage custom users for the application. The application is directly accessed using 

  • Work or school accounts, provisioned using Azure AD
  • Microsoft personal accounts e.g. outlook, hotmail, etc.

Using Microsoft Identity Platform with ASP.NET Core Application

The figure 1 shows an integration of Microsoft Identity Platform with ASP.NET Core application


Figure 1: An integration between ASP.NET Core app with Microsoft Identity Platform   

The figure 1 explains complete mechanism of accessing the application with an integration with Microsoft Identity Platform. So lets implement all steps those are shown in figure 1

Step 1: To implement these steps, the Azure Subscription is required. Please visit this link to register for free to access Microsoft Azure Services. Once the Azure subscription is completed, login to the portal.
Step 2: Open Microsoft Visual Studio 2019 and create an ASP.NET Core application. Name this application as AAD_Web_App. Select the Authenticate Type as Microsoft Identity Platform as shown in figure 2


Figure 2: The ASP.NET Core app

 Once the project is created, expand the project dependencies, you can see that the Azure AD Authentication packages are added in the project as shown figure 3



Figure 3: The Azure AD Packages    

The Microsoft.AspNetCore.Authentication.AzureAD.UI package represents an ASP.NET Core Azure Active Directory Integration that is used for the application authentication using Azure AD users. This package depends on Microsoft.AspNetCore.Authentication.JwtBearer package. This is ASP.NET Core middleware. This middleware enables ASP.NET Core application to receive an OpenID Connect bearer token.  The other dependency package Microsoft.AspNetCore.Authentication.OpenIdConnect  is an ASP.NET Core middleware that enables the application to support the OpenID Connect authentication workflow. 

Open the appsettings.json file. This file contains settings for AzureAD integration as shown in listing 1


"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "qualified.domain.name",
    "TenantId": "22222222-2222-2222-2222-222222222222",
    "ClientId": "11111111-1111-1111-11111111111111111",
    "CallbackPath": "/signin-oidc"
  }

Listing 1: The application integration with AzureAD   

The settings in listing 1 needs to be provided with actual values of ClientId and TenantId. We can get these values from the Azure Portal.

Step 3: Select Azure Active Directory from the portal as shown in the figure 4



Figure 4: Selecting Azure Active Directory

Select App registrations from the Active Directory Page as shown in Figure 5



Figure 5: Selecting App Registration 

Select the New registration on the App registrations as shown in figure 6



Figure 6: New App Registration 

On the Register an application page, provide the user-facing application name of your choice. The most important settings here is the we have to mention the Supported account type. This settings is important using which we can set what types of users can access the application. The Redirect URL is optional we will set it afterwards. We will set the Supported account type as Accounts in this organizational directory only (Default directory only - Single tenant) as shown in figure 7



Figure 7: The Registration Page 

Click on the Register button. The application is registered and the new registered application page will show application details as shown in figure 8



Figure 8: The application registration 

Copy the Application ID (client id) and DirectoryID (tenant id) from this page. We will need this for integrating ASP.NET Core app with Azure AD.  On this Application Registration page click on Authentication link an then click on Add a platform as shown in figure 9



Figure 9: The Authentication configuration

The step of adding platform will allow us to select the type of application that will be targeted for integrating with Azure AD Identity. One we click on the Add a platform  the page will be displayed for configuring platform as shown in figure 10



Figure 10: Configure the platform      

We can target to various types of application for integration with AzureAD. On this page select Web. This means that we will be integrating a Web application with Azure AD. Once we click on the Web we need to configure Redirect URIs and select check boxes for Access Tokens and ID Tokens. To enter Redirect URIs, right-click on the ASP.NET Core Project and select properties. Select the Debug from the Properties page and copy the SSL url as shown in figure 11



Figure 11: Selecting the ASP.NET Core Applications URL for redirection    

As shown in figure 12, configure the Redirect URIs and Access token



Figure 12: Configuring the Web Application for Redirection 

Click on the Configure button to view the application configuration as shown in figure 13



Figure 13: The Complete Configuration

Once the Web app is configured, visit back to the Active directory page and click on Users link as shown in figure 14



Figure 14: The Users for Azure AD

Add a new used in the active directory as shown in the figure 15





Figure 15: Adding new user in the Azure AD

The figure 15 shows the Azure AD domain name in which the user will be created. We will use this domain name in the ASP.NET Core web application.

Step 4: Go back to the ASP.NET Core application. Modify the appsettings.json file by adding ClientId, TenantId and Domain. The ClientId and TenantId can be read from App Registration details as shown in Figure 8. The Domain name is shown in figure 15. While creating the ASP.NET Core application, since we have selected Authentication Type as Microsoft Identity Platform, the code for adding AzureAD is already generated in the ConfigureServices() method of the Startup class as shown in   Listing 2 


public void ConfigureServices(IServiceCollection services)
{
  services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
	.AddAzureAD(options => Configuration.Bind("AzureAd", options));

  services.AddRazorPages().AddMvcOptions(options =>
  {
	var policy = new AuthorizationPolicyBuilder()
				.RequireAuthenticatedUser()
				.Build();
    options.Filters.Add(new AuthorizeFilter(policy));
  });
}

Listing 2: The Authentication generated code 

The code in listing 2 uses the AzureAD authentication scheme by default and read the configuration from appsettings.json. The Razor page from application will be accessible only when the user is authenticated against the AzureAD.  The  The Configure() method of the Startup class already have middlewares to manage Authentication and Authorization. The Pages folder contains Shared sub-folder. This folder contains _LoginPartial.cshtml file. This file contains the code to show authenticated user name.

Run the application, the Microsoft Online Login Page will be loaded in the browser as shown in figure 16



Figure 16: The Microsoft Online Login Page

Enter the login information of the user created in the AzureAD as shown in figure 15. Once these credentials are validated, the Index page of the application will be rendered which shows login name as shown in figure 17



Figure 17: The successful login   

Once you click on Sign Out, the sign out page will be displayed.

This is how an integration between ASP.NET Core Web application is managed using an integration with AzureAD.

Conclusion: It is always better to integrate an AzureAD with web application which is hosted on Microsoft Azure platform for enhanced security. This integration allows Outlook, Hotmail, Skype, etc. users to access an application with their credentials and Microsoft Identity Platform have made this very easy. 

Popular posts from this blog

Uploading Excel File to ASP.NET Core 6 application to save data from Excel to SQL Server Database

ASP.NET Core 6: Downloading Files from the Server

ASP.NET Core 6: Using Entity Framework Core with Oracle Database with Code-First Approach