How to integrate Azure Active Directory with your ASP .Net Core project.

Javier Eduardo Mendoza Blandón
7 min readOct 2, 2023

--

Artículo en español / Spanish article

Welcome. This guide aims to teach a basic configuration to integrate your Azure Active Directory with your ASP .Net Core project in just 19 steps.

Requirements:

  • Active Azure account
  • Azure active directory
  • ASP NET Web Project
  • Basic knowledge of Visual Studio .NET 2022.
  • Visual Studio 2022 Version 17.5.4.
  • Dotnet version 6.0.16

Why Azure Active Directory ?

Using Azure Active Directory (Azure AD) for login in your ASP.NET Web project in your company can bring several benefits. Here are some reasons why you might consider using Azure AD:

  • Centralized Identity and Access Management
  • Scalability and Reliability
  • Integration with Microsoft Ecosystem
  • Developer-Friendly
  • Audit and Compliance
  • Single Sign-On (SSO) Experience
  • Security and Authentication Features

It’s important to assess your organization’s specific requirements and evaluate whether Azure AD aligns with your needs for identity and access management.

Lets start with this guide

Step 0: If you don’t have an ASP Net Web project, you can learn how to create one with this video tutorial. Otherwise, you can omit this step.

https://www.youtube.com/watch?v=x9txMQOT-wo

Step 1: Write “Azure Active Directory” in the input search

Step 2: Search on the aside options: Manage => App registrations

Step 3: Click the option button : + New registration

Step 4: Chose a representative name with an -ad at the end

If everything goes fine , you can have something like this screen.

Step 5: You’ll need to write the following data, from the last screen, because you will require this information.

"AzureAd": {

"Instance": "https://login.microsoftonline.com/",

"Domain": "<domain>.onmicrosoft.com",

"TenantId": "<tenantId>",

"ClientId": "<clientId>",

"CallbackPath": "/signin-oidc"

}
You can find your azure active directory domain , in the Overview option

Step 6: Search on the aside options: Manage => Authentication

Inside the app registration created before

Step 7: After clicking it there, you’ll need to add the following: additional web redirect uris, front channel logout URL, check the ID tokens checkbox, choose accounts in this organization, and finally save.

add signin-oidc to the url

Web => Redirect URIs is where you will need to add each URLs of your different environments for your application, for example: development, stage, and production.

Another example can be the step #19.

Step 8: Let’s open our ASP Net web project and add the following three NuGet packages:

Microsoft.AspNetCore.Authentication.AzureAd.UI

Microsoft.Identity.Web

Microsoft.Identity.Web.UI

Step 9: Let’s add on the appsettings.json the information about your Azure AD configuration previously saved by you in step #5.

The settings provided in the “AzureAd” section include:

  • “Instance”: The URL of the Azure AD authority, where users will authenticate.
  • “ClientId”: The client ID of the registered application in Azure AD, representing your application.
  • “TenantId”: The ID of the Azure AD tenant that your application belongs to.
  • “CallbackPath”: The URL to which the authentication response will be sent after a successful login.

Step 10: Let’s add the following code to you Program.cs class part 1.

// step 10.1
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));


// step 10.2
builder.Services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});


// step 10.3
builder.Services.AddRazorPages().AddMicrosoftIdentityUI();

step 10.1: In this step, we’re setting up the authentication for the ASP.NET Core application using Azure Active Directory (Azure AD) as the identity provider.

step 10.2: In this step, we’re enabling authorization for the application’s controllers. The AddControllersWithViews method configures the ASP.NET Core application to use controllers with views for handling HTTP requests.

step 10.3: In this step, we’re enabling Razor Pages for the application with Microsoft Identity UI integration. The AddRazorPages method sets up Razor Pages support in the ASP.NET Core application.

Step 11: Let’s add the following code to you Program.cs class part 2

// step 11.1
app.UseAuthentication();

// step 11.2
app.MapRazorPages();

step 11.1: In this step, we’re enabling the authentication middleware for the ASP.NET Core application. The UseAuthentication method is used to enable the authentication middleware in the application’s request processing pipeline.

step 11.2: In this step, we’re mapping the Razor Pages routes in the ASP.NET Core application. The MapRazorPages method is used to configure routing for Razor Pages.

Step 12: Let’s add the [Authorize] property for all those controllers we want to protect.

for example
[Authorize]

Step 13: Let’s create the following “UserAzureAD” model class to get some data about your user from your Azure AD after being authenticated.

Create the UserAzureAd class
 public class UserAzureAD
{
public string user_name { get; set; }
public string user_domain { get; set; }
public string user_email { get; set; }
}
result

Step 14: Let’s create a method to fill the object created before with the ClaimsPrincipal class.

/// <summary>
/// Get the user name, user domain and email of the user from the authentication claims
/// </summary>
/// <param name="user">Auth Claims</param>
/// <returns>Azure AD</returns>
public static UserAzureAD GetUserOnAzureAd(ClaimsPrincipal user)
{
var preferredUsernameClaim = user.Claims.FirstOrDefault(c => c.Type.Equals("preferred_username"));
if (preferredUsernameClaim != null)
{
return new UserAzureAD
{
user_name = user.Claims.FirstOrDefault(p => p.Type.Equals("name")).Value,
user_email = preferredUsernameClaim.Value,
user_domain = string.Format(@"cpiccr\{0}", preferredUsernameClaim.Value.Split('@')[0])
};
}
return null; // Or throw an exception if preferred_username claim is required
}

Step 15: Let’s implement the method created before to obtain the data from the user authenticated on Azure AD.

Can be wherever view you want, for this exercise will be this.
@using WebAppWithAD.Controllers

<hr/>
@if (User.Identity.IsAuthenticated)
{
var getUser = @HomeController.GetUserOnAzureAd(User);

<h4> Azure AD User name: @getUser.user_name </h4>
<h4> Azure AD Email: @getUser.user_email </h4>
<h4> Azure AD User domain: @getUser.user_domain</h4>

<a class="nav-link" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">
Sign Out (X)
</a>
}
result

Looks like everything es ready to test.

Step 16: Let’s test our local implementation to verify if our integration with Azure AD is working as expected.

remember to use your business email associated with your Azure AD account.
rember your password
If you look at the “NewWebsite.ad” is the same configured in step #4 before.
NO
Looks like eveything goes fine.

Step 17: Let’s test if the “Sign Out” functionality is working as expected.

click on Sing Out
working fine

Step 18: Let’s test if the “Sign In” functionality is working as expected.

Can be wherever view you want, for this exercise will be this.

add the following code

 @if (!User.Identity.IsAuthenticated)
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Iniciar sesión</a>
</li>
}

Compile, run the code and repeat the step 16.

You should see this option now , let’s do a click

Step 19: Let’s deploy your project on Azure App Service with Azure Cloud to verify if everything will continue working as expected.

If you don’t have one , here is the official documentation of how to do it:

after the deployment , you will see the following screen

So, you’ll need to repeat these steps: #2, #6, #7, but with your Azure App service URL or Default domain.

Save and after do a website refresh and repeat this step: #17.

You will see something like this.

Please try to test the following steps: #17, #18 by yourself to verify that everything is working as expected on the Azure Web Site.

Looks like everything is working as expected after completed the integration of the Azure Active Directory with an ASP .Net Core project. It was successful on Local and cloud environments, here is the public repository if you want to take a look:

Please, let me know your feedback because I can grow with it, thank you very much.

My apologies for any inadvertent errors with my English skills, I’m currently learning how to speak my second language.

--

--