Home C# / .NET Blazor Authentication and Authorization: A Complete Guide
Advanced 3 min · July 13, 2026

Blazor Authentication and Authorization: A Complete Guide

Learn how to implement authentication and authorization in Blazor Server and WebAssembly apps.

N
Naren Founder & Principal Engineer

20+ years shipping production .NET services in enterprise systems. Drawn from code that ran under real load.

Follow
Production
production tested
July 13, 2026
last updated
2,043
articles · all by Naren
Before you start⏱ 20-25 min read
  • Basic knowledge of C# and ASP.NET Core
  • Familiarity with Blazor basics (components, routing)
  • Understanding of HTTP and REST APIs
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • Use AuthenticationStateProvider to get user state.
  • Blazor Server uses SignalR; protect circuit with AuthorizeView.
  • Blazor WebAssembly uses JWT tokens; store securely.
  • Implement custom policies with AuthorizationHandler.
  • Always validate on server side even if client checks pass.
✦ Definition~90s read
What is Blazor Authentication and Authorization?

Blazor authentication and authorization is the process of verifying user identity and controlling access to components and data in Blazor applications.

Think of authentication like showing your ID at a club entrance to prove who you are, and authorization like the wristband color that determines which rooms you can enter.
Plain-English First

Think of authentication like showing your ID at a club entrance to prove who you are, and authorization like the wristband color that determines which rooms you can enter. In Blazor, the app checks your ID (authentication) and then decides what parts of the UI you can see or what actions you can perform (authorization).

In modern web applications, controlling access to features and data is critical. Blazor, Microsoft's framework for building interactive web UIs with C#, offers robust authentication and authorization mechanisms. Whether you're building a Blazor Server app where UI logic runs on the server, or a Blazor WebAssembly app that runs entirely in the browser, you need to ensure that only authenticated users can access protected resources and that they have the right permissions. This tutorial covers both hosting models, from integrating ASP.NET Core Identity to using JWT tokens and custom policies. You'll learn how to secure your Blazor components, handle authentication state, and avoid common pitfalls. By the end, you'll be able to implement a complete authentication and authorization system that is both secure and maintainable.

Understanding Authentication and Authorization in Blazor

Authentication is the process of verifying who a user is, while authorization determines what an authenticated user is allowed to do. In Blazor, these concepts are implemented using ASP.NET Core's built-in authentication middleware and the AuthorizeView component. Blazor Server uses a persistent SignalR connection, so authentication state is managed on the server. Blazor WebAssembly runs entirely in the browser, so authentication relies on tokens (typically JWT) stored in the browser. Both models support cookie-based authentication and external providers like Google or Microsoft. Understanding the hosting model is crucial because it affects how you manage authentication state and protect resources.

Startup.csCSHARP
1
2
3
4
5
6
7
8
// Blazor Server - Configure Services
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/login";
        options.AccessDeniedPath = "/access-denied";
    });
services.AddAuthorization();
🔥Hosting Model Matters
📊 Production Insight
In Blazor Server, be aware that the circuit can be reconnected after a temporary disconnection. The authentication state is preserved as long as the circuit is alive. In WebAssembly, tokens can be stolen via XSS; always sanitize inputs and use secure storage.
🎯 Key Takeaway
Choose the authentication approach based on your Blazor hosting model: cookies for Server, JWT for WebAssembly.

Setting Up ASP.NET Core Identity with Blazor

ASP.NET Core Identity provides a complete user management system including registration, login, password reset, and role management. To integrate with Blazor, you need to scaffold Identity and then create Blazor components that interact with it. For Blazor Server, you can use the built-in Identity UI or create custom pages. For Blazor WebAssembly, you typically use a separate API project that handles authentication and issues JWT tokens. Below is an example of configuring Identity in a Blazor Server app.

Program.csCSHARP
1
2
3
4
5
6
7
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddAuthentication();
builder.Services.AddAuthorization();
💡Scaffold Identity
📊 Production Insight
When using Identity with Blazor Server, ensure that the Identity UI pages are not conflicting with Blazor routing. Use the @page directive carefully.
🎯 Key Takeaway
ASP.NET Core Identity integrates seamlessly with Blazor Server, providing a robust authentication system out of the box.

Using AuthorizeView and the [Authorize] Attribute

Blazor provides two primary ways to control access: the AuthorizeView component and the [Authorize] attribute. AuthorizeView is used in Razor markup to conditionally render content based on the user's authentication status and roles. The [Authorize] attribute can be applied to pages (components with @page) to restrict access entirely. You can also specify roles or policies. Here's an example of both.

AdminPage.razorCSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@page "/admin"
@attribute [Authorize(Roles = "Admin")]

<h3>Admin Panel</h3>
<p>Welcome, @context.User.Identity.Name!</p>

<AuthorizeView Roles="Admin">
    <Authorized>
        <button @onclick="DeleteAllUsers">Delete All Users</button>
    </Authorized>
    <NotAuthorized>
        <p>You do not have permission to delete users.</p>
    </NotAuthorized>
</AuthorizeView>

@code {
    private void DeleteAllUsers() { /* ... */ }
}
⚠ Server-Side Validation Required
📊 Production Insight
In Blazor Server, the [Authorize] attribute works because the component runs on the server. In Blazor WebAssembly, it's a client-side check; you must still protect your API endpoints.
🎯 Key Takeaway
Use AuthorizeView for conditional UI and [Authorize] for page-level protection.

Implementing Custom Authorization Policies

Sometimes role-based authorization is not enough. You may need to check specific claims or complex conditions. ASP.NET Core allows you to define custom policies using the AuthorizationHandler. For example, you might want to allow only users who are both in the 'Admin' role and have a 'Department' claim of 'IT'. Here's how to implement a custom policy.

DepartmentRequirement.csCSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class DepartmentRequirement : IAuthorizationRequirement
{
    public string Department { get; }
    public DepartmentRequirement(string department) => Department = department;
}

public class DepartmentAuthorizationHandler : AuthorizationHandler<DepartmentRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, DepartmentRequirement requirement)
    {
        if (context.User.IsInRole("Admin") &&
            context.User.HasClaim(c => c.Type == "Department" && c.Value == requirement.Department))
        {
            context.Succeed(requirement);
        }
        return Task.CompletedTask;
    }
}

// Register in Program.cs
builder.Services.AddSingleton<IAuthorizationHandler, DepartmentAuthorizationHandler>();
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("ITAdmin", policy =>
        policy.Requirements.Add(new DepartmentRequirement("IT")));
});
💡Policy-Based Authorization
📊 Production Insight
Avoid putting too much logic in authorization handlers; keep them focused on checking claims. Use dependency injection for services if needed.
🎯 Key Takeaway
Custom policies allow fine-grained access control based on claims and complex logic.

Blazor WebAssembly JWT Authentication

In Blazor WebAssembly, authentication is typically done via JWT tokens. The client app sends a login request to a server API, receives a token, and then includes that token in subsequent requests. The token is stored in the browser's localStorage or sessionStorage. Blazor provides the AuthenticationStateProvider to manage the authentication state. Here's a simplified example of a custom AuthenticationStateProvider for JWT.

JwtAuthenticationStateProvider.csCSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class JwtAuthenticationStateProvider : AuthenticationStateProvider
{
    private readonly HttpClient _httpClient;
    private readonly ILocalStorageService _localStorage;

    public JwtAuthenticationStateProvider(HttpClient httpClient, ILocalStorageService localStorage)
    {
        _httpClient = httpClient;
        _localStorage = localStorage;
    }

    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        var token = await _localStorage.GetItemAsync<string>("authToken");
        if (string.IsNullOrWhiteSpace(token))
            return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));

        var claims = ParseClaimsFromJwt(token);
        var identity = new ClaimsIdentity(claims, "jwt");
        var user = new ClaimsPrincipal(identity);
        return new AuthenticationState(user);
    }

    public void NotifyUserAuthentication(string token)
    {
        var claims = ParseClaimsFromJwt(token);
        var identity = new ClaimsIdentity(claims, "jwt");
        var user = new ClaimsPrincipal(identity);
        NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(user)));
    }

    public void NotifyUserLogout()
    {
        NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))));
    }

    private IEnumerable<Claim> ParseClaimsFromJwt(string jwt)
    {
        // Implement JWT parsing logic
    }
}
⚠ Token Storage Security
📊 Production Insight
Always validate the token on the server side. Implement token refresh to avoid expiration issues. Use secure storage mechanisms.
🎯 Key Takeaway
JWT authentication in Blazor WebAssembly requires a custom AuthenticationStateProvider to manage token lifecycle.

Protecting API Endpoints and Server-Side Validation

No matter how well you protect the Blazor UI, you must always validate authorization on the server. API endpoints should be protected with the [Authorize] attribute and appropriate policies. In Blazor Server, the server-side code is already protected, but in WebAssembly, the client-side checks are merely cosmetic. Always assume that a malicious user can bypass client-side checks. Here's an example of a protected API endpoint.

WeatherForecastController.csCSHARP
1
2
3
4
5
6
7
8
9
10
11
12
[ApiController]
[Route("api/[controller]")]
[Authorize(Policy = "ITAdmin")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        // Only IT Admins can access this
        return new List<WeatherForecast>();
    }
}
🔥Defense in Depth
📊 Production Insight
Use the same policy names on both client and server to avoid confusion. Consider using a shared constants class.
🎯 Key Takeaway
Server-side authorization is mandatory. Never trust client-side validation alone.

Handling Authentication State Changes and Logout

When a user logs out, you need to clear the authentication state and redirect appropriately. In Blazor Server, you can use the SignOutAsync method from the HttpContext. In Blazor WebAssembly, you need to clear the token from storage and notify the AuthenticationStateProvider. Here's an example of logout in Blazor WebAssembly.

Logout.razorCSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
@inject IJwtAuthenticationStateProvider AuthStateProvider
@inject NavigationManager Navigation

<button @onclick="Logout">Logout</button>

@code {
    private async Task Logout()
    {
        await _localStorage.RemoveItemAsync("authToken");
        AuthStateProvider.NotifyUserLogout();
        Navigation.NavigateTo("/");
    }
}
💡Redirect After Logout
📊 Production Insight
In Blazor Server, ensure that the logout also invalidates the authentication cookie. Use the built-in Identity UI for consistency.
🎯 Key Takeaway
Logout must clear all authentication state and redirect to a public page.
● Production incidentPOST-MORTEMseverity: high

The Unauthorized Admin: A Blazor Authorization Bypass

Symptom
Users with 'User' role could navigate to '/admin' and see admin-only content.
Assumption
The developer assumed that hiding the admin menu link was sufficient protection.
Root cause
The AuthorizeView component was used only to conditionally show UI elements, but the route was not protected with the [Authorize] attribute or policy checks.
Fix
Added [Authorize(Roles = "Admin")] to the admin page component and implemented a server-side validation in the API endpoints.
Key lesson
  • Never rely solely on UI hiding for security; always enforce authorization on the server.
  • Use [Authorize] attribute on Blazor components and pages.
  • Validate permissions on API calls even if the client checks pass.
  • Test authorization with different user roles during development.
  • Consider using policy-based authorization for fine-grained control.
Production debug guideSymptom to Action3 entries
Symptom · 01
User is redirected to login page repeatedly even after logging in.
Fix
Check if the authentication state is being persisted correctly. In Blazor Server, ensure the circuit is not reconnecting. In WebAssembly, verify token storage and expiration.
Symptom · 02
AuthorizeView shows 'Not authorized' for authenticated users.
Fix
Verify that the user's claims include the required roles or policies. Check the AuthenticationStateProvider implementation.
Symptom · 03
API calls return 401 Unauthorized despite user being logged in.
Fix
Ensure the token is being sent in the request header. Check token expiry and refresh logic.
★ Quick Debug Cheat SheetCommon authentication issues and immediate fixes.
User not recognized after login
Immediate action
Check AuthenticationStateProvider.GetAuthenticationStateAsync()
Commands
Console.WriteLine(state.User.Identity.IsAuthenticated);
Console.WriteLine(string.Join(", ", state.User.Claims.Select(c => c.Type)));
Fix now
Ensure the authentication state is being updated after login.
AuthorizeView always shows 'Not authorized'+
Immediate action
Check the Roles or Policies in AuthorizeView
Commands
Check if user has the required claim: state.User.IsInRole("Admin")
Verify policy: await authorizationService.AuthorizeAsync(state.User, "MyPolicy")
Fix now
Add missing claims or correct the role/policy name.
API calls fail with 401+
Immediate action
Check if token is attached to HttpClient
Commands
Console.WriteLine(httpClient.DefaultRequestHeaders.Authorization);
Check token expiry: var jwt = new JwtSecurityTokenHandler().ReadJwtToken(token); Console.WriteLine(jwt.ValidTo);
Fix now
Implement token refresh logic or re-authenticate.
FeatureBlazor ServerBlazor WebAssembly
Authentication MechanismCookies (ASP.NET Core Identity)JWT Tokens
State ManagementServer-side circuitClient-side (browser)
Token StorageCookie (httpOnly)localStorage/sessionStorage
Authorization EnforcementServer-side (built-in)Client-side (must also secure API)
Offline SupportNoYes (if PWA)
⚙ Quick Reference
7 commands from this guide
FileCommand / CodePurpose
Startup.csservices.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)Understanding Authentication and Authorization in Blazor
Program.csbuilder.Services.AddDbContext(options =>Setting Up ASP.NET Core Identity with Blazor
AdminPage.razor@page "/admin"Using AuthorizeView and the [Authorize] Attribute
DepartmentRequirement.cspublic class DepartmentRequirement : IAuthorizationRequirementImplementing Custom Authorization Policies
JwtAuthenticationStateProvider.cspublic class JwtAuthenticationStateProvider : AuthenticationStateProviderBlazor WebAssembly JWT Authentication
WeatherForecastController.cs[ApiController]Protecting API Endpoints and Server-Side Validation
Logout.razor@inject IJwtAuthenticationStateProvider AuthStateProviderHandling Authentication State Changes and Logout

Key takeaways

1
Authentication and authorization are separate concerns; both must be implemented correctly.
2
Use AuthorizeView for UI and [Authorize] for page/component protection.
3
Always validate authorization on the server side, especially in WebAssembly apps.
4
Custom policies provide fine-grained access control beyond roles.
5
Secure token storage is critical in Blazor WebAssembly; prefer httpOnly cookies.

Common mistakes to avoid

3 patterns
×

Relying solely on AuthorizeView to hide UI elements without server-side protection.

×

Storing JWT tokens in localStorage without considering XSS.

×

Not handling token expiration in Blazor WebAssembly.

INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
Explain the difference between authentication and authorization in Blazo...
Q02SENIOR
How would you implement a custom authorization policy that checks a user...
Q03SENIOR
What are the security implications of using Blazor WebAssembly with JWT ...
Q01 of 03JUNIOR

Explain the difference between authentication and authorization in Blazor.

ANSWER
Authentication verifies the identity of the user (who they are), while authorization determines what resources or actions the user is allowed to access. In Blazor, authentication is handled by the AuthenticationStateProvider, and authorization is enforced via AuthorizeView and the [Authorize] attribute.
FAQ · 3 QUESTIONS

Frequently Asked Questions

01
Can I use the same authentication code for both Blazor Server and WebAssembly?
02
How do I refresh JWT tokens in Blazor WebAssembly?
03
Is it safe to store JWT tokens in localStorage?
N
Naren Founder & Principal Engineer

20+ years shipping production .NET services in enterprise systems. Drawn from code that ran under real load.

Follow
Verified
production tested
July 13, 2026
last updated
2,043
articles · all by Naren
🔥

That's ASP.NET. Mark it forged?

3 min read · try the examples if you haven't

Previous
Blazor Forms and Validation
22 / 35 · ASP.NET
Next
Blazor Rendering Modes in .NET 8/9