Implement Entra ID Auth in Blazor with FluentUI and ASP.NET Core Razor
Introduction
In today's digital landscape, secure and seamless authentication is paramount for web applications. Many developers rely on ASP.NET Core Identity for managing user accounts, but transitioning to Single Sign-On (SSO) via Azure Entra ID (formally known as Azure AD) offers enhanced security features like conditional access and streamlined user management. A recent project required migrating from ASP.NET Core Identity to Entra ID to leverage these benefits, including the ability to use conditional access policies and unified account management.
However, finding clear and concise tutorials on this topic was challenging. Many available resources are cluttered with excessive configurations, lack clarity, or omit essential features like role management. This blog post aims to provide a straightforward guide to implementing Entra ID authentication in a Blazor application using FluentUI. Additionally, the approach is compatible with ASP.NET Core Razor applications, making it versatile for various project types.
Prerequisites
Before we begin, ensure you have the following:
- Development environment: Visual Studio 2022 or later with .NET 8.0 SDK installed.
- Azure subscription: Access to the Entra ID portal to configure Entra ID.
- Basic knowledge: Familiarity with Blazor, ASP.NET Core, and C#.
Setting up the Blazor project
First, let's create a new Blazor Web App project targeting .NET 8.0.
Create a new blazor project
Open your terminal and run the following commands:
dotnet new install Microsoft.FluentUI.AspNetCore.Templates
dotnet new fluentblazor --name DemoApplication
If you prefer a standalone WebAssembly project, use:
dotnet new fluentblazorwasm --name DemoApplication
Installing Necessary NuGet Packages
Navigate to your project directory and install the required NuGet packages:
dotnet add package Microsoft.Identity.Web
dotnet add package Microsoft.Identity.Web.UI
dotnet add package Microsoft.AspNetCore.Authentication.AzureAD.UI
These packages enable integration with Entra ID, providing authentication and authorization features out of the box.
Configuring Entra AD
Registering the application in Entra ID
- Access Azure Portal: Navigate to the Azure Portal and sign in with your credentials.
- Entra ID Directory: Go to Azure Entra ID > App registrations.
- New Registration:
- Name: Choose a display name for your application (e.g., DemoApplication).
- Supported Account Types: Select Single tenant.
- Redirect URI:
- For HTTPS: https://localhost:7240/signin-oidc
- For HTTP (development): http://localhost:5131/signin-oidc
- Register: Click Register to create the application.
Configuring app roles
App Roles:
- In your registered app, navigate to App roles.
- Click Create app role and fill in the details:
- Display name: Writers
- Allowed member types: User/Groups
- Value: DemoApplication.Incidents.Writers
Assigning Roles:
- Go to Enterprise applications > DemoApplication > Users and groups.
- Click Add user, select the user, and assign the Writers role.
Obtaining essential IDs
From the Overview page of your app registration, copy the Directory (tenant) ID and Application (client) ID. These will be needed for configuration.
Configuring the Blazor Application
Update appsettings.json
Add your Azure AD configuration to appsettings.json:
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "yourdomain.com",
"TenantId": "your-tenant-id",
"ClientId": "your-client-id",
"CallbackPath": "/signin-oidc"
}
}
Replace "your-tenant-id" and "your-client-id" with the values obtained earlier.
Update Program.cs
Configure authentication and authorization services in Program.cs:
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy =>
policy.RequireRole("Admin"));
options.AddPolicy("ManagerOnly", policy =>
policy.RequireRole("Manager"));
options.AddPolicy("UserOnly", policy =>
policy.RequireRole("User"));
});
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
.AddMicrosoftIdentityConsentHandler();
builder.Services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
builder.Services.AddFluentUIComponents();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();
Creating a Blazor Component with Role-Based Authorization
Create a new Blazor component, for example, Test.razor:
@page "/IncidentManagement"
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize(Roles = "Admin,DemoApplication.Incidents.Writers")]
<h3>Incident Management</h3>
<!-- Your component code goes here -->
Handling authentication issues
During development, you might encounter an error like:
OpenIdConnectProtocolException: Message contains error: 'unsupported_response_type',
error_description: 'AADSTS700054: response_type 'id_token' is not enabled for the application.
Solution
- Enable ID tokens:
- Go to Azure Active Directory > App registrations > YourAppName > Authentication.
- Under Advanced settings, check the box ID tokens to enable implicit grant.
- Update Manifest:
- This action sets
oauth2AllowIdTokenImplicitFlow
totrue
in the manifest file.
- This action sets
- Restart Application:
- Restart your Blazor application to apply the changes.
Running the application
Start your application using Visual Studio or the terminal:
dotnet run
Navigate to https://localhost:7140/Test and sign in with an Azure AD account that has the appropriate roles assigned. You should be prompted to accept consent, after which you can access the protected page.
Summary
Transitioning to Azure AD for authentication in your Blazor or ASP.NET Core Razor applications not only enhances security but also simplifies user management through SSO and conditional access policies. This guide provided a straightforward approach to integrating Azure AD with role-based authorization, leveraging FluentUI for a modern Microsoft application look and feel user interface.