Secure Your Applications with Azure Active Directory Authentication

This tutorial guides you through integrating Azure Active Directory (Azure AD) for user authentication in your web applications, enhancing security and simplifying user management.

1. Understanding Azure AD Authentication

Azure Active Directory (Azure AD) is a cloud-based identity and access management service. It enables your employees to sign in and access resources, such as Microsoft 365 and a vast number of other SaaS applications. You can also use Azure AD to enable sign-in to your own custom applications.

Key benefits include:

2. Prerequisites

Before you begin, ensure you have the following:

3. Registering Your Application in Azure AD

The first step is to register your application within your Azure AD tenant. This process provides your application with a unique identifier (Application ID) and allows Azure AD to issue security tokens.

  1. Navigate to the Azure portal.
  2. Search for and select "Azure Active Directory".
  3. Under "Manage", click on "App registrations".
  4. Click "New registration".
  5. Provide a name for your application (e.g., "MySecureWebApp").
  6. Select the supported account types. For most scenarios, "Accounts in this organizational directory only" is sufficient.
  7. Under "Redirect URI", select "Web" and enter the URL where your application will be accessible after successful authentication. This is crucial for Azure AD to know where to send the authentication response. For local development, it might look like https://localhost:5001/signin-oidc.
  8. Click "Register".

After registration, you will see the Application (client) ID. Make a note of this ID, as you'll need it later.

4. Implementing Authentication Flow

Azure AD supports several authentication protocols, including OAuth 2.0 and OpenID Connect (OIDC). Most modern web applications use OIDC, which is built on top of OAuth 2.0 and provides identity information.

Using Microsoft Authentication Library (MSAL)

The Microsoft Authentication Library (MSAL) simplifies the process of acquiring security tokens from Azure AD and provides access to Microsoft Graph API or your own web APIs.

Recommendation: Use MSAL for your development language and platform for the most streamlined experience. Find the appropriate MSAL library for JavaScript, Python, .NET, and others.

The typical authentication flow involves:

  1. Initiating an authentication request from your application.
  2. Redirecting the user to the Azure AD login page.
  3. The user authenticates with their Azure AD credentials.
  4. Azure AD redirects the user back to your application's registered Redirect URI with an authorization code or tokens.
  5. Your application exchanges the code for tokens (access token, ID token, refresh token).
  6. You validate the tokens and use the information (e.g., user ID, roles) to personalize the user experience or authorize access to resources.

5. Example: ASP.NET Core Integration

Here's a simplified example of how to configure Azure AD authentication in an ASP.NET Core application using the Microsoft.Identity.Web NuGet package.

Install NuGet Package

dotnet add package Microsoft.Identity.Web
dotnet add package Microsoft.Identity.Web.UI

Configure Services (Startup.cs or Program.cs)

In your Startup.cs or Program.cs file, configure authentication:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAD");

    services.AddControllersWithViews();
    services.AddRazorPages();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ... other configurations
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });
}

Configuration in appsettings.json

Add your Azure AD application details to appsettings.json:

{
  "AzureAD": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "your-tenant.onmicrosoft.com",
    "TenantId": "YOUR_TENANT_ID",
    "ClientId": "YOUR_CLIENT_ID",
    "CallbackPath": "/signin-oidc"
  }
}

Replace your-tenant.onmicrosoft.com, YOUR_TENANT_ID, and YOUR_CLIENT_ID with your actual Azure AD values.

Protecting Controllers/Pages

Use the [Authorize] attribute to protect access to controllers or specific actions:

[Authorize]
public class HomeController : Controller
{
    // ... actions
}

6. Token Validation and Claims

Once a user is authenticated, Azure AD issues an ID token containing claims about the user (e.g., name, email, unique object ID). You can access these claims within your application to personalize content or make authorization decisions.

In ASP.NET Core, you can access claims from the User principal:

public IActionResult Profile()
{
    var userName = User.FindFirst("name").Value;
    var userObjectId = User.FindFirst(System.Security.Claims.ClaimTypes.ObjectIdentifier).Value;
    // ... display user information
    return View();
}

You can also request specific scopes to get an access token, which can be used to call protected APIs, such as Microsoft Graph.

7. Advanced Topics and Best Practices

Learn More: For detailed API references and advanced scenarios, consult the official Azure AD developer documentation.

By implementing Azure AD authentication, you significantly improve the security posture of your applications and provide a seamless user experience.