Introduction

In the previous article Authorization Code Flow Azure Ad, we learned the most important concepts about the Authorization Code Flow in Azure Ad. In this post, we will cover Blazor Server App Authentication with Entra ID by enabling the user to authenticate via the Microsoft Identity Platform with a secure authentication flow such as the Authorization Code Flow.

Take a look at the finished Blazor Server App Authentication with Entra ID example implemented in ASP.Net Core 8 and Azure Ad (Entra ID).

https://dotnetcoder.com/wp-content/uploads/2024/10/Blazor-Server-App-Authentication-with-Entra-ID-in-action.webm

Setting up the Blazor Server App Authentication with Entra ID project

To implement Blazor Server App Authentication with Entra ID in practice , open Visual Studio and create a blank solution named BlazorEntra  as shown below.

Adding the blazor server app


Then add a new Blazor Web App project template named Dnc.BlazorWebApp and select .NET 8 (Long Term Support) as the target Framework.

 select .NET 8 (Long Term Support) as the target Framework.

Finally , click on Create.

Blazor Entra Solution

Registering the Blazor Web App in Microsoft Entra ID (Azure Ad)

To get started with Blazor Server App Authentication with Entra ID, we need to register our app with a Microsoft Entra tenant.

You need An Azure account, subscription, go to the Azure Portal .
Go to Azure Active Directory “Entra ID” in the left navigation pane and click “App Registrations” and then click “New Registration” as shown below.

Add new app registration

Second: Enter the following information (See below).

Entering the required information in app registration blade


Finally, click “Register”.

The registered Blazor App overview

Find the application (client) ID and the required information in the overview bar and make a note of it. You will use these values later in your code in the configuration files of your application.

Also read https://dotnetcoder.com/creating-a-reusable-blazor-search-component/

Generate App Client Secret

In the app’s registration screen, go to the “Certificate and Secrets” blade on the left to open the page where you can generate secrets, then click “New Client Secret” as shown below.

Certificate and Secrets  blade

Enter the required information, then click “Add” as shown below.

Adding a new secret

Copy the key and save it in a safe place. This key is no longer visible after you have closed the tile.

Configuring the Blazor Web App

Now that our app is registered, we can start integrating the Microsoft Entra ID into the Blazor app. To do this, we first need to install some NuGet packages.

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.10" />
  <PackageReference Include="Microsoft.Identity.Web" Version="3.2.2" />
  <PackageReference Include="Microsoft.Identity.Web.UI" Version="3.2.2" />
</ItemGroup>

To implement Blazor Server App Authentication with Entra ID, we first need to configure our Azure AD credentials in the appsettings.Development.json file as shown below.

"EntraId": {
  "ClientId": "faa6297e-fde6-4966-9bc1-8b058426c2ce",
  "ClientSecret": "Glg8Q~GrOA-DkjpfUDQykVl19iPGOkbPcgOf-bfg",
  "Domain": "{YOUR DOMAIN}",
  "TenantId": "{YOUR TENANT}",
  "ResponseType": "code",
  "CallbackPath": "/signin-oidc",
  "Instance": "https://login.microsoftonline.com/"
}

Finally, update the Program.cs file by adding the following code.

// Removed code for brevity
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(options =>
    {
        options.ClientId = builder.Configuration.GetValue<string>("EntraId:ClientId");
        options.ClientSecret = builder.Configuration.GetValue<string>("EntraId:ClientSecret");
        options.TenantId = builder.Configuration.GetValue<string>("EntraId:TenantId");
        options.ResponseType = builder.Configuration.GetValue<string>("EntraId:ResponseType");
        options.Domain = builder.Configuration.GetValue<string>("EntraId:Domain");
        options.Instance = builder.Configuration.GetValue<string>("EntraId:Instance");
        options.CallbackPath = builder.Configuration.GetValue<string>("EntraId:CallbackPath");
    });

builder.Services.AddAuthorization();
builder.Services.AddHttpContextAccessor();

builder.Services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();

// Removed code for brevity

app.MapControllers();

// Removed code for brevity

The following line adds the authentication services to the DI container and instructs the Blazor Server app to use the scheme OpenIdConnectDefaults.AuthenticationScheme to authenticate the user.

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)

OpenID Connect (OIDC) is an authentication protocol that builds on OAuth and allows applications to verify the identity of the user based on the actions performed by the authorization server.

while AddMicrosoftIdentityWebApp(options => { // removed code for brevity }) adds Microsoft Identity Platform as the authentication provider.

The following line of code adds the IHttpContextAccessor service in the dependency injection (DI) container that allows us to access the current HTTP context, which can be useful for various scenarios, such as retrieving logged in user information.

builder.Services.AddHttpContextAccessor()

The code below configures MVC services for the app and creates a new authorization policy that requires the user to be authenticated before accessing any action and apply it as a global filter that enforces the specified authorization policy on every request.

builder.Services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();

The line below registers the routes for the controller actions otherwise, users will receive a 404 page when clicking on the Login link.

app.MapControllers();

Finally we need to add login and logout links. To do that open the MainLayout.razor and add the following code as shown below.

// Removed code for brevity 
<main>
    <div class="top-row px-4">
        <CascadingAuthenticationState>
            <AuthorizeView>
                <Authorized>
                    <a asp-controller="Home" asp-action="Index">Welcome @context.User.Identity?.Name!</a>
                    <a href="MicrosoftIdentity/Account/SignOut">Logout</a>
                </Authorized>
                <NotAuthorized>
                    <a href="MicrosoftIdentity/Account/SignIn">Login</a>
                </NotAuthorized>
            </AuthorizeView>
        </CascadingAuthenticationState>
    </div>
    <article class="content px-4">
        @Body
    </article>
</main>
// Removed code for brevity

Blazor Server App Authentication with Entra ID Example is ready and we can now access the user’s information using the HttpContextAccessor as shown in the code below that I added to the Home.razor component.

@page "/"
@using Microsoft.AspNetCore.Components.Authorization
@inject IHttpContextAccessor HttpContextAccessor
<PageTitle>Home</PageTitle>

<h3>User’s information</h3>

@if (HttpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
{
    @if (claimsPrincipal != null && claimsPrincipal.Claims.Any())
    {
        <ul>
            @foreach (var claim in claimsPrincipal.Claims)
            {
                <li><pre>@claim.Type: @claim.Value</pre></li>
            }
        </ul>
    }
}
else
{
    <p>Login in to see User’s information</p>
}


@code {
    private System.Security.Claims.ClaimsPrincipal claimsPrincipal;

    protected override void OnInitialized()
    {
        var context = HttpContextAccessor.HttpContext;
        claimsPrincipal = HttpContextAccessor.HttpContext.User;
    }
}

Press F5 for lunch.

Blazor Server App Authentication with Entra ID in action

Conclusion

In this post, we implemented Blazor Server App Authentication with Entra ID using the Authorization Code Flow  to allow users to authenticate to Azure Ad before they can use the secure Blazor Server app.

Also read https://dotnetcoder.com/building-a-reusable-blazor-select-component/

Sample code

You can find the complete example code for Blazor Server App Authentication with Entra ID project on my GitHub repository

Author

Exit mobile version