Securing Blazor applications is a critical aspect of web development. ASP.NET Core provides robust mechanisms for handling authentication (verifying who a user is) and authorization (determining what a user is allowed to do).
Blazor offers flexible ways to integrate with various authentication providers and implement fine-grained authorization policies. This document will guide you through the key concepts and common patterns.
Authentication involves confirming the identity of a user. ASP.NET Core supports several authentication schemes, including:
When creating a new Blazor project, you can choose authentication templates. These templates automatically set up the necessary services, pages, and components, such as:
Login.razor
and Register.razor
for individual accounts.RedirectToLogin.razor
for handling unauthenticated access.LogOut.razor
for user sign-out.LoginDisplay.razor
to show login status and links.The core of Blazor's authentication relies on the Microsoft.AspNetCore.Components.Authorization
namespace and the AuthenticationStateProvider
service.
AuthenticationStateProvider
This is the central service for retrieving the authentication state of the current user. You can implement or use built-in providers.
To get the current user's identity:
@inject Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider AuthenticationStateProvider
@code {
private string userId;
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
userId = user.Identity.Name; // Or get user claims
}
else
{
userId = "Anonymous";
}
}
}
AuthorizeView
ComponentThe <AuthorizeView>
component conditionally renders content based on the user's authorization status. It can also be used to display different content for authenticated and unauthenticated users.
<AuthorizeView>
<Authorized>
<p>Hello, @context.User.Identity?.Name! You are logged in.</p>
<button>Access Protected Resource</button>
</Authorized>
<NotAuthorized>
<p>You are not logged in. Please <a href="/authentication/login">log in</a>.</p>
</NotAuthorized>
</AuthorizeView>
The context
within the <Authorized>
and <NotAuthorized>
templates represents the AuthenticationState
.
Authorization determines if an authenticated user has permission to access a resource or perform an action. ASP.NET Core offers several authorization models:
You can protect entire Blazor pages or components using the [Authorize]
attribute.
@page "/admin"
@attribute [Authorize] // Requires authentication
@attribute [Authorize(Roles = "Admin,SuperAdmin")] // Requires user to be in Admin or SuperAdmin role
@using Microsoft.AspNetCore.Authorization
<h1>Administrator Dashboard</h1>
<p>This content is only visible to administrators.</p>
If a user is not authorized, they will be redirected to the login page (if configured) or receive a "401 Unauthorized" or "403 Forbidden" response.
Policies provide a more expressive way to define authorization requirements.
1. Define a Policy in Program.cs
(or Startup.cs
):
// In Program.cs (for .NET 6+)
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdminRole", policy =>
policy.RequireRole("Admin"));
options.AddPolicy("MinimumAge", policy =>
policy.RequireAssertion(context =>
{
// Example: Check a custom claim for age
var ageClaim = context.User.FindFirst("Age");
if (ageClaim != null && int.TryParse(ageClaim.Value, out int age))
{
return age >= 18;
}
return false;
}));
});
2. Apply the Policy in Blazor:
// Using a page attribute
@page "/special-offer"
@attribute [Authorize(Policy = "MinimumAge")]
<h1>Special Offer Page</h1>
<p>This page is for users aged 18 and above.</p>
// Using AuthorizeView
<AuthorizeView Policy="RequireAdminRole">
<p>Welcome, Administrator! You have access to administrative functions.</p>
</AuthorizeView>
For complex scenarios, you can create custom IAuthorizationRequirement
classes and corresponding AuthorizationHandler
implementations.
This is powerful for scenarios like resource-based authorization (e.g., "Can user X edit document Y?") or complex business rule checks.
The implementation details can vary slightly between Blazor WebAssembly (client-side) and Blazor Server (server-side/hosted).
InteractivePrerendered
hosting model shares some server-side benefits.When using Blazor WebAssembly, your application interacts with backend APIs. These APIs must be secured using standard ASP.NET Core authentication and authorization middleware. Your Blazor app needs to include the authentication token (e.g., JWT) in API requests.
// In Blazor WebAssembly project's Program.cs or App.razor
builder.Services.AddOidcAuthentication(options =>
{
// Configure OIDC client settings
builder.Configuration.Bind("LocalRelyingParty", options.ProviderOptions);
});
// When making an HTTP request
@inject HttpClient Http
// ... later in your component
var response = await Http.GetAsync("api/data"); // HttpClient is configured with the auth token
You might need to create a custom AuthenticationStateProvider
if you're not using standard ASP.NET Core Identity or need to integrate with a custom authentication system.
The custom provider must be registered as a singleton service in Program.cs
.
[Authorize]
attribute for page and component-level protection.<AuthorizeView>
for fine-grained control over UI rendering based on authorization.