ProudMonkey

ASP.NET Core and Blazor Code Venture: Configuring Azure AD Authentication

Advertise here. Contact me at vmsdurano at gmail dot com.

Introduction

If you stumble upon this article, then I presume you are new to Blazor and would like to get your hands dirty with the practical examples. Just like you, I am also pretty much new to Blazor and that’s why I am writing this series of articles as a reference to other ASP.NET developers who might want to jump on Blazor.

This is the first article of the ASP.NET Core and Blazor Code Venture series. The goal of this article series is to build a data driven Blazor app from scratch starting from setting up your development workspace, authentication, data access with CRUD, consuming Rest API’s and down to deployment. In order to cover most of the real-world scenarios in a typical secured web app, we will build a simple To-Do Web app which enables users to submit requests and then notify admin with the requests so they can act on it. You can think of this app as an internal tool that will be used within your organization to handle issues that the users encounter. We will try to incorporate as much features in the app as we go along but, in this series, we will start with the authentication piece.

Background

Early last year Microsoft announce a new experimental project from the ASP.NET team called Blazor. Blazor is an experimental web UI SPA framework based on C#, Razor, and HTML that runs in the browser via WebAssembly without JavaScript. Yes, you heard that right – without JavaScript! That being said. Around April 2019, Blazor was officially released as a Preview. This means that Blazor is no longer experimental and will probably be officially released after .NET Core 3.0.

Prior to this article, I’ve been exploring Blazor a bit when it was still an experimental release, and I personally find the framework very interesting so I thought of writing an eBook about it to share what I have learned. I think Blazor is going to be incredibly a hit and that's because I see WebAssembly as actually superseding JavaScript. Sure, JavaScript and its frameworks aren't going anywhere, but why would you teach a new programmer JavaScript when you can just teach them C#, Python, etc. and have them work with simpler tools in a more performant environment?

Setup the Development Environment

Let’s go ahead and install the required tools and SDKs needed for building the Blazor app. If you already have installed the tools mentioned in the list below, then you may skip this step but just make sure you update them to the latest version as possible.

Prerequisites

Framework and Tools Installed

The following frameworks and tools are automatically installed after installing the .NET Core 3.0 Preview and Blazor bits:

  • Microsoft Visual Studio Professional 2019 Preview (Version 16.2.0 Preview 2.0)
  • Microsoft .NET Core (Version 3.0.0-preview6-27804-01)
  • ASP.NET Core Blazor Language Services (Version 16.0.19307.2)
  • ASP.NET and Web Tools 2019 (Version 16.2.159.22830)
  • ASP.NET Web Framework and Tools 2019 (Version 16.2.159.22830)

Once you have successfully installed the prerequisites above, then let’s go ahead and start the adventure!

Setup Azure Active Directory

The very first thing that we need to setup here is an Active Directory hosted in Azure for us to test the user Authentication in our application later. If you have an Azure AD already setup by your company or admin, then you may skip this section and jump directly to the next step. In summary, what you will need to setup to enable Azure AD Authentication are the following parameters:

  • Domain Name
  • Tenant ID
  • Client ID

Now, if you want to explore Azure AD by yourself and get a feel on how to setup a simple Active Directory in Azure, then let’s move on. 😊

Login through the Azure portal here: https://azure.microsoft.com/en-us/

After logging in, click on the Portal link located at the upper right corner of the website as shown in the figure below:

Figure 1: Azure Portal Website

When you’re in the Azure Portal, click on the Azure Active Directory link as shown in the figure below:

Figure 2: Azure Portal Website - Active Directory page

On the next screen, click on Create a Directory link just like in the figure below:

Figure 3: Azure Portal Website - Create a Directory

Now, enter a unique Organization and Domain name for your directory. In this example, I have used the following values:

Figure 4: Azure Portal Website - Create a new Directory

Please keep note of the domain name as we will be using it when setting up the authentication in the application.

When you are satisfied with the values provided, just click the Create button to setup the directory for you. Normally, the setup will take about just one minute. Sometimes you may have to wait a bit as it could take a few minutes to complete the setup depending on your internet speed.

When it’s done, a notification should be displayed in the portal as shown in the figure below:

Figure 5: Azure Portal Website - New Directory Created

Create a New User

Next is we are going to create a couple of test users within the directory that we have just created.

Now click on the link that says “Click here to Manager your Active Directory” or just click on the “Azure Active Directory” link. It should take you the Active Directory Domain that we have just created.

Click on the User link as shown in the figure below:

Figure 6: Azure Portal Website - Create New Users

Let's create a few test users by entering the names and their email addresses or usernames as shown in the figure below:

Figure 7: Azure Portal Website - Create New Users

You can create a few users or more, but for this exercise, I’m just going to create two users:

  • User
  • Admin

With these two users configured, we would be able to test the app with normal users and admin roles in the later part of the series. You can see the list of all users that you have created by navigating through the “All Users” link as shown in the figure below:

Figure 8: Azure Portal Website - List of Users

Server-Side Blazor Authentication with Azure AD

In this exercise, we will explore Azure AD authentication. Let’s take a look at how we can do this with Blazor.

Mid of 2019, Microsoft shipped ASP.NET Core 3.0 Preview 6, with the red-hot Blazor project getting built-in support for handling authentication and authorization, among other updates. Microsoft said:

"The server-side Blazor template now supports options for enabling all of the standard authentication configurations using ASP.NET Core Identity, Azure AD, and Azure AD B2C. We haven't updated the Blazor WebAssembly templates to support these options yet, but we plan to do so after .NET Core 3.0 has shipped."

For more details on this release, see: ASP.NET Core and Blazor updates in .NET Core 3.0 Preview

This simply means for us .NET developers that Authentication and Authorization can now be easily integrated into our Blazor apps with any configuration types you want. So without further ado, let’s try out Azure AD authentication in Blazor.

Fire-up Visual Studio 2019 Preview and then create a new project just like in the figure below:

Figure 9: Visual Studio - Create New Project

Select ASP.NET Core Web Application work load just like in the figure below and then click Next:

Figure 10: Visual Studio - Create New ASP.NET Core Web App

Set a name for your project to whatever you want and then click Create. It should now bring you to the following screen:

Figure 11: Visual Studio - Configure New Project

Select Blazor (server-side) template from the list as shown in the figure below and then click the Change link under Authentication:

Figure 12: Visual Studio - New Blazor (Server-side)

On the next screen, select Work or School Accounts and then supply the Domain name that you configured from Azure portal:

Figure 13: Visual Studio - Change Authentication

Once you’ve finished setting up the authentication, click the Create button to let Visual Studio scaffold the necessary files for you. When successful, you should be able to see something like this:

Figure 14: Visual Studio - Default Generated Files

You will see the “Microsoft.AspNetCore.Authentication.AzureAD.UI” NuGet package added as project dependency. This package provides components for integrating Azure Active Directory authentication within our ASP.NET Core app easily.

The LoginDisplay.razor page is also created for us and contains the following Blazor markup:

<AuthorizeView>  
    <Authorized>
        Hello, @context.User.Identity.Name!
        <a href="AzureAD/Account/SignOut">Log out</a>
    </Authorized>
    <NotAuthorized>
        <a href="AzureAD/Account/SignIn">Log in</a>
    </NotAuthorized>
</AuthorizeView>  

The markup above uses the Blazor AuthorizeView component that displays the UI depending on whether the user is authenticated and authorize to see page or not. The component exposes a context variable of type AuthenticationState (@context.User.Identity.Name), which you can use to access information about the signed-in user.

Now in appsettings.json file, you will also find the following configuration generated:

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "theproudmonkey.onmicrosoft.com",
    "TenantId": "123XXXXX-12XX-12XX-12XX-123456XXXXXX",
    "ClientId": "123XXXXX-12XX-12XX-12XX-123456XXXXXX"
},

The JSON configuration above defines our Azure AD configuration. Please note that you must change the value of TenantId and ClientId with the actual values you have. This configuration will be called at ConfigureServices() method in Startup.cs file which gets called at runtime:

public void ConfigureServices(IServiceCollection services){  
        services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
                .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
        services.AddControllers();
}

The code above adds the authentication service middleware using AzureADDefaults.BearerAuthenticationScheme which is the default scheme for Azure AD bearer. It then calls the AddAzureADBearer() method and binds the “AzureAd” configurations from the appsettings.json file.

Behind the scenes, Visual Studio automatically registers our ASP.NET Core app in Azure AD App Registration. You can verify this by navigating back to the Azure Portal > Azure Active Directory > App Registrations:

Figure 15: Azure Portal Website - App Registrations

First Run

To use Azure Active Directory for logging users in, the application should run using SSL (https). By the default, the project is configured with SSL so there’s no need for us to configure it.

Now to ensure that our application is working with Azure AD authentication, let’s test it. Build the application then run the application by hitting CTRL + F5 keys.

Figure 16: Running the App - AD Login

Enter you Microsoft AD account and then click Next. It will take to to the next screen to enter the corresponding password:

Figure 17: Running the App - AD Login

When your login is successful, it should take you to the default page of the Blazor app just like in the figure below:

Figure 18: Running the App - Successful Login

Clicking the Log out link will produce the following output:

Figure 19: Running the App - Successful Logout

That’s it! With just a few clicks, we now have a Blazor app up and running with Azure AD authentication. Visual Studio does all the job by connecting the pieces together behind the scenes for enabling authentication without doing any much coding on our side. That’s sweet!

Stay tuned for the next article!

Summary

In this series we’ve learned how to setup an Azure Active Directory by creating a new tenant an users. We also learned how to create a simple Blazor app and authenticate users using their Azure AD credentials.

Buy Me A Coffee