Introduction
If you're developing an ASP.NET Core web app, you may need to implement secure authentication for your users. Azure Active Directory (AAD) is a cloud-based identity and access management service that provides secure authentication for your applications. In this article, we will cover how to implement AAD authentication in your ASP.NET Core web app.
Prerequisites
- An Azure subscription
- An ASP.NET Core web app
- .NET 6 or later
Register your web app in AAD
To register your web app in AAD:




- In the Azure portal, go to "Azure Active Directory" and select "App registrations".
- Select "New registration" and follow the prompts.
- Under "New registration", add a "Give your application name,Redirect URI" for your web app.
- Make note of the "Application (client) ID" and "Directory (tenant) ID" values, as you will need them later.
Add AAD authentication to your web app
To add AAD authentication to your web app:
Copyservices.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "domainname.onmicrosoft.com",
"ClientId": "404bc5e0-29c8-49da-bb1f-ssssdsds",
"TenantId": "93d9a3f7-7fa5-4ab8-b552-sdsdsdsds"
}
Copy
app.UseAuthentication();
app.UseAuthorization();
Copy
- In your ASP.NET Core web app, install the Microsoft.AspNetCore.Authentication.AzureAD.UI NuGet package.
- In your app's Startup.cs file, add the following code to the ConfigureServices method:
- Add "AzureAd" configuration in the appsetting.json.
- In the Configure method, add the following code:
- Add the `[Authorize]` attribute to controllers or controller methods that require authentication.
Adding Authentication to Controllers and Views
Now that you have configured authentication and authorization, you can add it to your controllers and views. Here's how:
[Authorize]
public class HomeController : Controller
{
//...
}
Copy
@@if (User.Identity.IsAuthenticated)
{
<p> Welcome, @@User.Identity.Name! </p>
}
else
{
<p> Please sign in. </p>
}
Copy
- In your controller, add the `[Authorize]` attribute to require authentication:
- In your view, use the `User.Identity.IsAuthenticated` property to check if the user is authenticated:
Conclusion
Implementing Azure Active Directory authentication in your ASP.NET Core web app can provide secure authentication for your users. By following the steps outlined in this article, you can configure AAD authentication and add it to your controllers and views. Remember to keep your app registration information and authentication settings secure to protect your users' data.
Good Article
Pradeep Gupta
1/10/2025