Click here to Skip to main content
15,867,568 members
Articles / Hosted Services / Azure

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
5 Aug 2019CPOL10 min read 18.4K   172   11   9
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 APIs and down to deployment.

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 APIs 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 many features in the app as we go along but, in this series, we will start with the authentication piece.

Background

Early last year, Microsoft announced 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. 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 that 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:

Image 1

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:

Image 2

Figure 2: Azure Portal Website - Active Directory page

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

Image 3

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:

Image 4

Figure 4: Azure Portal Website - Create a new Directory
Quote:

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:

Image 5

Figure 5: Azure Portal Website - New Directory Created

Create a New User

Next, 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 to the Active Directory Domain that we have just created.

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

Image 6

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:

Image 7

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:

Image 8

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:

Image 9

Figure 9: Visual Studio - Create New Project

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

Image 10

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:

Image 11

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:

Image 12

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:

Image 13

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:

Image 14

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:

Razor
<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:

JavaScript
"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:

C#
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:

Image 15

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 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.

Image 16

Figure 16: Running the App - AD Login

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

Image 17

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:

Image 18

Figure 18: Running the App - Successful Login

Clicking the Logout link will produce the following output:

Image 19

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 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.

History

  • 5th August, 2019: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
A code monkey who loves to drink beer, play guitar and listen to music.

My Tech Blog: https://vmsdurano.com/
My Youtube Channel: https://www.youtube.com/channel/UCuabaYm8QH4b1MAclaRp-3Q

I currently work as a Solutions Architect and we build "cool things" to help people improve their health.

With over 14 years of professional experience working as a Sr. Software Engineer specializing mainly on Web and Mobile apps using Microsoft technologies. My exploration into programming began at the age of 15;Turbo PASCAL, C, C++, JAVA, VB6, Action Scripts and a variety of other equally obscure acronyms, mainly as a hobby. After several detours, I am here today on the VB.NET to C# channel. I have worked on Web Apps + Client-side technologies + Mobile Apps + Micro-services + REST APIs + Event Communication + Databases + Cloud + Containers , which go together like coffee crumble ice cream.

I have been awarded Microsoft MVP each year since 2009, awarded C# Corner MVP for 2015, 2016,2017 and 2018, CodeProject MVP, MVA, MVE, Microsoft Influencer, Dzone MVB, Microsoft ASP.NET Site Hall of Famer with All-Star level and a regular contributor at various technical community websites such as CSharpCorner, CodeProject, ASP.NET and TechNet.

Books written:
" Book: Understanding Game Application Development with Xamarin.Forms and ASP.NET
" Book (Technical Reviewer): ASP.NET Core and Angular 2
" EBook: Dockerizing ASP.NET Core and Blazor Applications on Mac
" EBook: ASP.NET MVC 5- A Beginner's Guide
" EBook: ASP.NET GridView Control Pocket Guide

Comments and Discussions

 
QuestionCalling other apis with the signed in user token Pin
Member 1462838618-Jan-20 9:32
Member 1462838618-Jan-20 9:32 
QuestionMultiple Blazor Apps, Sign Out Issue Pin
Member 1421337723-Oct-19 8:05
Member 1421337723-Oct-19 8:05 
AnswerRe: Multiple Blazor Apps, Sign Out Issue Pin
Vincent Maverick Durano3-Dec-19 15:20
professionalVincent Maverick Durano3-Dec-19 15:20 
Interesting findings! I haven't tried that scenario and I haven't deep dived into the details of Azure AD yet, so I can't give you answer to that at the moment.
QuestionUser Role Pin
foluis21-Oct-19 10:22
foluis21-Oct-19 10:22 
AnswerRe: User Role Pin
Vincent Maverick Durano3-Dec-19 15:26
professionalVincent Maverick Durano3-Dec-19 15:26 
QuestionWhat is next? Pin
MSBassSinger16-Oct-19 5:55
professionalMSBassSinger16-Oct-19 5:55 
AnswerRe: What is next? Pin
Vincent Maverick Durano3-Dec-19 15:17
professionalVincent Maverick Durano3-Dec-19 15:17 
QuestionCan I do this in Chrome? Pin
Kevin O'Grady6-Aug-19 5:55
Kevin O'Grady6-Aug-19 5:55 
AnswerRe: Can I do this in Chrome? Pin
Vincent Maverick Durano6-Aug-19 8:18
professionalVincent Maverick Durano6-Aug-19 8:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.