Authenticate users with Azure Active Directory in ASP.NET Core

ASP.NET Core web applications often need to authenticate users accessing the application. There are many authentication schemes you can use to accomplish this task. One of them is authenticating using Azure Active Directive (Azure AD). ASP.NET Core project templates provide an easy way to integrate Azure AD authentication in an application. However, there are a few steps you need to perform before going ahead with the integration process. To that end this article explains what those steps are and how to complete the integration.

Create active directory

To begin, sign-in to Azure portal and select Azure Active Directory option from the left side pane.

Then locate the "Create a directory" option from right side bottom area of the page.

In the Create directory form enter some organization name, initial domain name, and also 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 which you can use for authentication.

Create a user account in the directory

Next, navigate to the newly created active directory and click on the Users option.

Then click on New User button at the top and create a new user account by entering the required user details.

Here on this screen, enter some user display name and user name. For example, if your initial domain name was ABCD then user name would be user2@ABCD.onmicrosoft.com. Make sure to use your correct initial domain name. Also, check the Show Password checkbox and note down this initial password (you can also copy it if you want). You will need this password when you sign-in for the first time. You are then required to change the password.

Clicking on the Create button will create the user account.

Register your web app with active directory

Now you need to register your web application with the Active Directory so that you can integrate AD authentication in it. To do so, go to directory's overview page and click on App registrations option.

On Register an application page enter some application name. Enter Redirect URL as https://localhost:1234/signin-oidc (change port number as per your setup). Also check the Access tokens and ID tokens checkboxes under advanced settings section. Keep other defaults unchanged and click on Register button.

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

 Make sure they are set to true. This completes Azure level tasks. Now let's move on to creating an ASP.NET Core web application that integrates AD authentication.

Create a new ASP.NET Core MVC web app

The simplest way to integrate AD into an ASP.NET Core app is to specify 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. However, in this example we deliberately won't use this selection. Rather we will create the application without authentication support and then manually wire AD authentication. The result will be quite similar to using the built-in template but we will be able to learn the process clearly.

So, stick to No Authentication option and create a new MVC web application.

Add required NuGet package and configure the app

Once the project is created, open the Manage NuGet Packages page and install this NuGet package: Microsoft.AspNetCore.Authentication.AzureAD.UI

After adding this package open the appsettings.json file and add the following section to it:

"AzureAD": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "YOUR_INITIAL_DOMAIN_HERE",
  "TenantId": "YOUR_TENANTID_HERE",
  "ClientId": "YOUR_CLIENTID_HERE"
}

As you can see, you need to mention your initial domain name, tenant ID, and client ID values there.

Next, open Startup class and write this code in ConfigureServices() method.

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(AzureADDefaults.
AuthenticationScheme)
        .AddAzureAD(options => Configuration.Bind
("AzureAD", options));
    ...
}

Notice that AddAzureAD() method supplies configuration settings specified in the AzureAD section of 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();
    });
}

Add Index(), SignOut(), and SignOutSuccess() actions to HomeController

Now open HomeController and add three actions as shown below:

[Authorize]
public IActionResult Index()
{
    ViewBag.UserName = User.Identity.Name;
    return View();
}

[HttpPost]
public IActionResult SignOut()
{
    return SignOut(new AuthenticationProperties() 
    { RedirectUri = "/Home/SignOutSuccess" }, 
AzureADDefaults.AuthenticationScheme, 
AzureADDefaults.CookieScheme, 
AzureADDefaults.OpenIdScheme);
}

public IActionResult SignOutSuccess()
{
    return View();
}

Notice these actions carefully. The Index() action is a secured action that can be accessed only by authenticated users. So, it is decorated with [Authorize] attribute. Currently signed in user's name is stored in ViewBag so that it can be displayed in a welcome message. Once a user successfully signs into the system he is shown Index page (discussed shortly). The Index page has Sign Out button that POSTs to the SignOut() action of HomeController.

The SignOut() action does the job of signing the user out of the system. It does so using SignOut() method and passing a series of authentication schemes to sign out from. When you enable Azure AD based authentication these three schemes are registered and hence all of them are specified here. Note that a RedirectUri is also specified in the SignOut() method. Upon successful sign-out user will be redirected to this URL.

The SignOutSuccess() action simply displays a success message to the user (discussed shortly).

Add Index and SignOutSuccess views

Now open Index.cshtml file and add this markup to it:

<h1>Welcome @ViewBag.UserName</h1>

<form asp-action="SignOut" asp-controller="Home">
    <button type="submit">Sign Out</button>
</form>

This markup is quite straightforward and displays a welcome message along with the Sign Out button.

Then add SignOutSuccess.cshtml and write this markup in it:

<h1>Sign Out Successful!</h1>

<a href="/Home/Index">Go To Index Page</a>

This completes the application. Now we are ready to test it.

Run the application

Set breakpoints at the beginning of Index(), SignOut(), and SignOutSuccess() methods and press F5. Since Index() is decorated with [Authorize] attribute, you will be automatically redirected to login page as shown below.

Here, enter the same user name that you created earlier (such as user2@YOUR_INITIAL_DOMAIN.onmicrosoft.com) and click on Next button. Then enter password (you will need to change the password when you sign-in for the first time).

Upon clicking the Sign In button you will be taken to the Index page where a welcome message is shown along with Sign Out button (part of  the user name is truncated to accommodate the iamge).

Click on the Sign Out button to sign out of the system and display a success message as shown velow.

If you click on the Go To Index Page link you will be required to sign in again.

That's it for now! Keep coding!!


Bipin Joshi is a software consultant, trainer, author, and yoga mentor having 24+ years of experience in software development, consulting, and training. He conducts instructor-led online training courses in ASP.NET Core, ASP.NET MVC, and Design Patterns for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get article updates : Facebook  Twitter  LinkedIn

Posted On : 12 August 2019


Tags : ASP.NET ASP.NET Core MVC C# Visual Studio


Subscribe to our newsletter

Get monthly email updates about new articles, tutorials, code samples, and how-tos getting added to our knowledge base.

  

Receive Weekly Updates