Integrating Azure Active Directory with your app

Introduction

One of the primary concerns for businesses using online services is ensuring that their user’s credentials and data are secure. As a developer, one way to address this concern is by integrating Azure Active Directory (Azure AD) with your app.

Azure AD is a cloud-based identity and access management service that enables you to manage user identities and access to resources in your app. It provides a single sign-on experience for users, multi-factor authentication, role-based access control, and many other features.

In this tutorial, we’ll walk you through the process of integrating Azure AD with your app. We’ll cover the following topics:

  1. Creating an Azure AD tenant and registering your app
  2. Configuring Azure AD for your app
  3. Authenticating users with Azure AD
  4. Securing resources with Azure AD

Prerequisites

To follow this tutorial, you’ll need the following:

  • An Azure account
  • Visual Studio or any other code editor
  • Basic knowledge of ASP.NET Core

Step 1: Creating an Azure AD tenant and registering your app

Let’s start by creating an Azure AD tenant and registering your app. An Azure AD tenant is a dedicated instance of an Azure Active Directory that your organization controls and manages. It’s used to store information about your organization’s users, groups, and applications.

To create an Azure AD tenant, follow these steps:

  1. Log in to the Azure portal (https://portal.azure.com).
  2. Click “Create a resource” in the top left corner, and search for “Azure Active Directory”.
  3. Click on “Create” to create a new Azure AD tenant.
  4. Fill in the required details and click “Create”.

Once the Azure AD tenant is created, let’s register your app with Azure AD. To do that, follow these steps:

  1. On the Azure portal, go to the Azure Active Directory instance you just created.
  2. Click on “App registrations” in the left-hand navigation menu.
  3. Click on “New registration” to register your app.
  4. Fill in the required details and select “Web” as the type of application you’re building.
  5. Enter the sign-on URL for your app. This is the URL that Azure AD will redirect users to after they sign in.
  6. Click on “Register” to create your app in Azure AD.

Step 2: Configuring Azure AD for your app

Now that your app is registered with Azure AD, you need to configure Azure AD for your app.

  1. Open your app’s code in Visual Studio or any other code editor.
  2. Install the “Microsoft.AspNetCore.Authentication.AzureAD.UI” package using NuGet.
  3. In the “appsettings.json” file, add the Azure AD configuration settings as shown below:
"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "<your-tenant-name>.onmicrosoft.com",
    "ClientId": "<your-client-id>",
    "TenantId": "<your-tenant-id>"
}

Here are the descriptions of each configuration setting:

  • Instance: The URL of the Azure AD instance.
  • Domain: The name of your Azure AD tenant.
  • ClientId: The client ID of your app, which you can find on the app registration page in the Azure portal.
  • TenantId: The ID of your Azure AD tenant, which you can also find on the app registration page.
  1. In the “Startup.cs” file, add the following code to configure Azure AD authentication:
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
    .AddAzureAD(options => Configuration.Bind("AzureAd", options));

services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
});

This code configures Azure AD as the authentication scheme for your app and sets up a fallback policy that requires users to be authenticated.

  1. Finally, decorate any controllers or actions in your app that need authentication with the “Authorize” attribute. For example:
[Authorize]
public class HomeController : Controller
{
    // ...
}

Step 3: Authenticating users with Azure AD

With Azure AD authentication configured, let’s authenticate users with Azure AD.

  1. Add a “Login” button to your app that redirects users to the Azure AD login page. The URL for the login page is:
https://login.microsoftonline.com/<your-tenant-name>.onmicrosoft.com/oauth2/v2.0/authorize

Make sure to replace “” with the name of your Azure AD tenant.

  1. When a user logs in successfully, Azure AD will redirect them back to the URL you specified in the app registration. You can handle this redirect by adding the following code to your app’s code:
[AllowAnonymous]
public async Task<IActionResult> SignIn()
{
    var redirectUrl = Url.Action(nameof(HomeController.Index), "Home");

    var authProperties = new AuthenticationProperties
    {
        RedirectUri = redirectUrl
    };

    return Challenge(authProperties, AzureADDefaults.AuthenticationScheme);
}

This code sets the URL that Azure AD will redirect users to after they sign in and uses the “Challenge” method to initiate the authentication process.

Step 4: Securing resources with Azure AD

Now that users can authenticate with Azure AD, let’s secure resources in your app.

  1. Add role-based access control to your app by defining roles in Azure AD and assigning them to users. You can do this by following these steps:
  • In the Azure portal, go to the app registration for your app.
  • Click on “Manifest” in the left-hand navigation menu.
  • Add the roles you want to use to the “appRoles” section of the manifest file. For example:
"appRoles": [
    {
        "allowedMemberTypes": [
          "User"
        ],
        "description": "Admins can manage the app.",
        "displayName": "Admin",
        "id": "1b4c2882-4825-43fa-840b-8e4ec1ab8abc",
        "isEnabled": true,
        "lang": null,
        "origin": "Application",


      "value": "admin"
    }
]
  • Assign roles to users in Azure AD by following these steps:
    • Go to the user’s profile in Azure AD.
    • Click on “Roles and administrators” in the left-hand navigation menu.
    • Click on “Add assignment” and select the roles you want to assign to the user.
  1. In your app’s code, use the “Authorize” attribute with role-based authorization to secure resources. For example:
[Authorize(Roles = "admin")]
public class AdminController : Controller
{
    // ...
}

This code restricts access to the “AdminController” to users who have the “admin” role assigned to them in Azure AD.

Conclusion

In this tutorial, we’ve shown you how to integrate Azure Active Directory with your app. By using Azure AD, you can provide your users with a secure, single sign-on experience and enhance the security of your app with multi-factor authentication and role-based access control.

Related Post