Authenticate Users With Azure Active Directory In ASP.NET Core 3.0

This time I was working with asp.net core 3.0 web application. So I was asked to implement authentication based on Azure Active Directory or Azure AD. So I was implementing this first time and faced a lot of issues while implementation. So thought I can create a blog to help others.

1. Create an active directory

Go ahead and log in to your Azure account and click on the Azure Active Directory from the left navigation panel.

Azure active directory

You will see a button to create a directory. Click on that will open a form enter some organization name, initial domain name, and also the select country. Remember the initial domain name because you will use it while creating users.

After entering these details click on Create button to create the directory. This AD will contain users and other details that you can use for authentication.

2. Create a user account in the directory

Now go ahead and navigate to the newly created active directory and click on the Users option.

Now click on the users and then Create new user button. It will open a new user form. Fill up the details.

Create a new active directory user

3. Register your web app with active directory

Once the app is registered with the AD, next you have to go to the app’s page and note down Client ID and Tenant ID generated during app registration. You will require these IDs in the ASP.NET Core app.

4. Create a new ASP.NET Core 3.0 web app

Open your visual studio and create a new .net core web application. While creating the ASP.NET Core app is to specify the authentication type during project creation (by clicking the Change link). You can either use Individual User Accounts or Work or School Accounts and specify AD details there.

5. Add required NuGet package and configure the app

Now go ahead and install the NuGet package into your project. Microsoft.AspNetCore.Authentication.AzureAD.UI

Once this package is installed open the appsettings.json file and add the following section to it:

  "AzureAd": {
        "Instance": "https://login.microsoftonline.com/",
        "Domain": "Your_Domain_Here",
        "TenantId": "Your_TenantId_Here",
        "ClientId": "Your_ClientId_Here",
        "CallbackPath": "/signin-oidc"
    },

You can get Domain, TenantId, ClientId from the Step 4 second picture. I have mentioned that already.

Now go to your Startup.cs and look for ConfigureServices() method.

     public void ConfigureServices(IServiceCollection services)
        {
            #region Active Directory Configuration
            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options));
            services.AddControllersWithViews();

            services.AddRazorPages();
        }

Notice that the AddAzureAD() method supplies configuration settings specified in the AzureAD section of the appsettings.json file.

Then go to Configure() method and ensure that calls to UseAuthentication() and UseAuthorization() exist there.

public void Configure(IApplicationBuilder app, 
IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }
    app.UseStaticFiles();
    app.UseRouting();

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

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

6. Add Controller code, Check [Authorize] attribute

Go to your HomeController and add [Authorize] attribute to the index method.

 [Authorize]
        public IActionResult Index()
        {
            return View();
        }

7. Run the application now

Now you should be good to go. Run the application and it will automatically navigate to the Azure login page. You have to put your azure ad username and password.

Posted by | View Post | View Group