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.
- Create a Web API project with Microsoft Identity Platform - Authentication type
- Register an Azure AD (AAD) app for the Web API.
- Create a Scope for App registration (API)
- Update the Web API Project to use Azure AD Authentication.
- Configure the Redirect URL's (If you are testing with Postman)
- 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.
app.settings.json
- "AzureAd": {
- "Instance": "https://login.microsoftonline.com/",
- "Domain": "*Your domain name*",
- "TenantId": "0000-00000-00000-0000",
- "ClientId": "0000-00000-00000-0000",
- "CallbackPath": "/signin-oidc"
WeatherController.cs
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Logging;
- using Microsoft.Identity.Web.Resource;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace AzureAD_OAuth_API.Controllers
- {
- [Authorize]
- [ApiController]
- [Route("[controller]")]
- public class WeatherForecastController : ControllerBase
- {
- private static readonly string[] Summaries = new[]
- {
- "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
- };
-
- private readonly ILogger<WeatherForecastController> _logger;
-
-
- static readonly string[] scopeRequiredByApi = new string[] { "ReadWriteAccess" };
-
- public WeatherForecastController(ILogger<WeatherForecastController> logger)
- {
- _logger = logger;
- }
-
- [HttpGet]
- public IEnumerable<WeatherForecast> Get()
- {
- HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);
-
- var rng = new Random();
- return Enumerable.Range(1, 5).Select(index => new WeatherForecast
- {
- Date = DateTime.Now.AddDays(index),
- TemperatureC = rng.Next(-20, 55),
- Summary = Summaries[rng.Next(Summaries.Length)]
- })
- .ToArray();
- }
- }
- }
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.
Conclusion
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 ....!