🔐 Enable Azure AD Authentication Using .Net 5.0 Web API

This article will brief you about setting up the Azure Active Directory in the Azure portal and integrate the Azure AD Authentication in our project. First, let's create an Azure Active Directory application that helps in protecting our web app.
Steps to Configure this are,
  1. Create a Web API project with Microsoft Identity Platform - Authentication type
  2. Register an Azure AD (AAD) app for the Web API.
  3. Create a Scope for App registration (API)
  4. Update the Web API Project to use Azure AD Authentication.
  5. Configure the Redirect URL's (If you are testing with Postman)
  6. Create a Client Secret.

Create a Web API project

Choose the Project Template
Name the project and solution and its saving location.
  • Choose the Target Framework - .Net 5.0 Current.
  • Change the Authentication Type - Microsoft Identity Platform 

Register an Azure AD (AAD) app for the Web API

To authenticate against Azure AD you need to add the Azure AD app registration and this can be done through the Azure portal at http://portal.azure.com  >  Azure Active Directory > App registrations > New application registration.
When the app registration is complete we can see the Client Id and Tenant Id in the Azure overview and copy those ID'd we will need in configuration setup.

Create Scope for App registration

The scope is required for authorizing the API like read and write access so we can define multiple scopes for our APIs if we are dealing with multiple projects or Microservices.
For that select the Expose an API  from the Azure _Auth application. Click on the + Add Scope button. where it will open the popup to create the scopes.

Update the Web API Project to use Azure AD Authentication

We need to configure the Azure active directory setup in appsettings.json like adding the application (client ID) and Tenant Id.
The Authentication type Microsoft.identity.platform helps in the integration of Azure AD and it will add all the basic configuration setup in the respective files.
  1. "AzureAd": {  
  2.     "Instance""https://login.microsoftonline.com/",  
  3.     "Domain""*Your domain name*"//Domain name configured in Azure  
  4.     "TenantId""0000-00000-00000-0000"// Tenant Id configured in Azure  
  5.     "ClientId""0000-00000-00000-0000"//  Client Id configured in Azure  
  6.     "CallbackPath""/signin-oidc"  
  1. using Microsoft.AspNetCore.Authorization;    
  2. using Microsoft.AspNetCore.Mvc;    
  3. using Microsoft.Extensions.Logging;    
  4. using Microsoft.Identity.Web.Resource;    
  5. using System;    
  6. using System.Collections.Generic;    
  7. using System.Linq;    
  8. using System.Threading.Tasks;    
  10. namespace AzureAD_OAuth_API.Controllers    
  11. {    
  12.     [Authorize]    
  13.     [ApiController]    
  14.     [Route("[controller]")]    
  15.     public class WeatherForecastController : ControllerBase    
  16.     {    
  17.         private static readonly string[] Summaries = new[]    
  18.         {    
  19.             "Freezing""Bracing""Chilly""Cool""Mild""Warm""Balmy""Hot""Sweltering""Scorching"    
  20.         };    
  22.         private readonly ILogger<WeatherForecastController> _logger;    
  24.         // The Web API will only accept tokens 1) for users, and 2) having the "access_as_user" scope for this API    
  25.         static readonly string[] scopeRequiredByApi = new string[] { "ReadWriteAccess" };    
  27.         public WeatherForecastController(ILogger<WeatherForecastController> logger)    
  28.         {    
  29.             _logger = logger;    
  30.         }    
  32.         [HttpGet]    
  33.         public IEnumerable<WeatherForecast> Get()    
  34.         {    
  35.             HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);    
  37.             var rng = new Random();    
  38.             return Enumerable.Range(1, 5).Select(index => new WeatherForecast    
  39.             {    
  40.                 Date = DateTime.Now.AddDays(index),    
  41.                 TemperatureC = rng.Next(-20, 55),    
  42.                 Summary = Summaries[rng.Next(Summaries.Length)]    
  43.             })    
  44.             .ToArray();    
  45.         }    
  46.     }    
  47. }     

Configure the Redirect URL's (If you are testing with Postman)

To test the APIs with Postman we need to configure the Callback URLs. Click on the Authentication menu, under the Platform Configurations, add the Redirect URLs - add the postman call back URL's - https://app.getpostman.com/oauth2/callback and application callback URL. 
Create Client Secret
And we can create the client secret using the certificates & secrets menu, add a new client secret. Set the description and duration as never. Add click on create it will create a token copy it. You won't see it again.

Setup the Authorization setup in Postman to test the API

We have completed the configuration for connecting the client using Postman. Now open Postman, provide the URL - https://localhost:*****/WeatherForecast, then select the Authorization tab and choose OAuth 2 from the Type list and choose Request Headers in Add authorization data to the Values for Authorization in Postman.
  • Token name - Valid name 
  • Grant Type - Choose Authorization Type
  • callback URL - https://app.getpostman.com/oauth2/callback 
  • Auth URL - https://login.microsoftonline.com/*Tenant ID*/oauth2/v2.0/authorize
  • Access Token URL - https://login.microsoftonline.com/*Tenant ID*/oauth2/v2.0/token
  • Client ID - Client ID > Azure portal
  • Client Secret - Secret Value > Azure portal 
Once you fill up all the fields - you can skip the State field, click on the Get New Access Token button. It will popup the Azure AD login dialog and you can log in. Once the login is completed, Postman will show a Token, which can be used to talk to the API.
Azure Portal > Login
It will authenticate based on your credentials and once the Authentication completes it will redirect to the token page. 
Below is the token generated by authenticating with our credentials click on > Use Token > it will automatically add in the request header. 
After the successful Authentication, now we can send the GET request which will return the JSON result, like this.
GitHub - Source Code


I hope this article gives you a clear picture of how to set up the Azure AD in the Azure portal and authenticate the Web API using .Net 5.0. The next article will show you how we can integrate the Azure Ad Authentication with Swagger.
Happy Coding ....!