Introduction
Microsoft Entra ID (formerly Azure Active Directory) is Microsoft's cloud-based identity and access management service, helping organizations secure their applications and resources. It provides enterprise-grade authentication, single sign-on (SSO), and multi-factor authentication capabilities, making it an ideal choice for modern web applications.
Blazor Server is a powerful framework for building interactive web applications using C# instead of JavaScript. It runs on the server side with real-time communication to the browser via SignalR, offering a rich, interactive user experience while keeping your business logic secure on the server.
In this article, we'll see the complete process of integrating Microsoft Entra ID authentication into a Blazor Server application, enabling secure user login and logout functionality.
Prerequisites
• .NET 8.0 SDK or later
• Visual Studio 2022 or VS Code
• An Azure subscription with access to Microsoft Entra ID
• Basic knowledge of C# and Blazor
Integration
Step 1: Register an Application in Microsoft Entra ID
Before integrating authentication into your Blazor app, you need to register your application in Microsoft Entra ID:
1.1 Navigate to Azure Portal
Go to Microsoft Entra Admin Center
Sign in with your Azure account
1.2 Register a New Application
Select App registrations from the left menu
Click + New registration
Fill in the registration form:
Name: Enter a descriptive name (e.g., "MS_EntraID_Blazor_Server")
Supported account types: Choose "Accounts in this organizational directory only" for single-tenant, or select the appropriate option for your use case
Redirect URI: Select "Web" and enter https://localhost:5224/signin-oidc.
Note: Adjust the port if different
![Entra ID Registrattion]()
4.Click Register
1.3 Configure Authentication Settings
After registration, you'll be taken to the app overview page:
Note down the following values (you'll need them later):
Application (client) ID
Directory (tenant) ID
Step 2: Set Up Your Blazor Server Application
Now let's configure the Blazor Server application to use Microsoft Entra ID authentication.
2.1 Install Required NuGet Packages
Add the below Microsoft Identity Web packages to your project
2.2 Configure Application Settings
Update your appsettings.json with the Azure AD configuration values from Step 1.3:
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "yourdomain.onmicrosoft.com",
"TenantId": "your-tenant-id",
"ClientId": "your-client-id",
"CallbackPath": "/signin-oidc"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Replace the placeholder values:
yourdomain.onmicrosoft.com - Your Azure AD domain
your-tenant-id - The Directory (tenant) ID
your-client-id - The Application (client) ID
2.3 Configure Program.cs
Update your Program.cs file to add authentication services and middleware:
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using MS_EntraID_Blazor.Components;
var builder = WebApplication.CreateBuilder(args);
// Add authentication services with MS Entra ID
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddAuthorization();
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
builder.Services.AddCascadingAuthenticationState();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.Run();
AddMicrosoftIdentityWebApp() configures OpenID Connect authentication
AddCascadingAuthenticationState() enables authentication state throughout your components
AddMicrosoftIdentityUI() provides the authentication controllers
Middleware order matters: Authentication before Authorization
2.4 Update _Imports.razor
Add the necessary using statements to
@using Microsoft.AspNetCore.Components.Authorization
Step 3: Create Login and Logout UI Components
3.1 Create LoginDisplay Component
Create a new file LoginDisplay.razor
@using Microsoft.AspNetCore.Components.Authorization
<AuthorizeView>
<Authorized>
<div class="user-info">
<span class="user-name">Hello, @context.User.Identity?.Name!</span>
<form action="MicrosoftIdentity/Account/SignOut" method="post">
<button type="submit" class="btn btn-link nav-link">Logout</button>
</form>
</div>
</Authorized>
<NotAuthorized>
<a href="MicrosoftIdentity/Account/SignIn" class="btn btn-primary">Login</a>
</NotAuthorized>
</AuthorizeView>
<style>
.user-info {
display: flex;
align-items: center;
gap: 1rem;
}
.user-name {
font-weight: 500;
color: #333;
}
.btn-link {
background: none;
border: none;
color: #0066cc;
text-decoration: none;
cursor: pointer;
padding: 0.375rem 0.75rem;
font-size: 1rem;
}
.btn-link:hover {
text-decoration: underline;
color: #0052a3;
}
.btn-primary {
background-color: #0066cc;
color: white;
padding: 0.5rem 1.5rem;
border-radius: 4px;
text-decoration: none;
border: none;
cursor: pointer;
font-weight: 500;
}
.btn-primary:hover {
background-color: #0052a3;
}
</style>
<AuthorizeView> - Displays different content based on authentication state
<Authorized> - Shows when user is logged in (displays username and logout button)
<NotAuthorized> - Shows when user is not logged in (displays login button)
The form posts to MicrosoftIdentity/Account/SignOut for logout
The link navigates to MicrosoftIdentity/Account/SignIn for login
3.2 Integrate LoginDisplay into MainLayout
Update MainLayout.razor to include the LoginDisplay component:
@inherits LayoutComponentBase
<div class="page">
<div class="sidebar">
<NavMenu />
</div>
<main>
<div class="top-row px-4">
<LoginDisplay />
<a href="https://learn.microsoft.com/aspnet/core/" target="_blank">About</a>
</div>
<article class="content px-4">
@Body
</article>
</main>
</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="" class="reload">Reload</a>
<a class="dismiss">🗙</a>
</div>
The <LoginDisplay /> component is now placed in the top navigation bar, making it accessible from every page.
Step 4: Protect Your Pages
You can protect specific pages or components using the [Authorize] attribute or <AuthorizeView> component.
Using the Authorize Attribute
Add to the top of any Razor component
@page "/weather"
@attribute [Authorize]
<PageTitle>Weather</PageTitle>
<h1>Weather</h1>
<!-- Rest of your component -->
Using AuthorizeView in Components
For fine-grained control within a component:
<AuthorizeView>
<Authorized>
<p>You are logged in as @context.User.Identity?.Name</p>
<!-- Protected content here -->
</Authorized>
<NotAuthorized>
<p>Please log in to view this content.</p>
</NotAuthorized>
</AuthorizeView>
Run and test your application
![App]()
Summary
We have seen what Microsoft Entra ID is and how it provides enterprise-grade security for your Blazor applications with minimal code. The Microsoft.Identity.Web library handles the complexities of OpenID Connect authentication, token management, and user claims, allowing you to focus on building your application's features. Whether you're building an internal business application or a customer-facing solution, Microsoft Entra ID integration with Blazor Server provides a robust foundation for secure, modern web applications.
Download the source code