Blazor Authentication and Authorization: A Complete Guide
Learn how to implement authentication and authorization in Blazor Server and WebAssembly apps.
20+ years shipping production .NET services in enterprise systems. Drawn from code that ran under real load.
- ✓Basic knowledge of C# and ASP.NET Core
- ✓Familiarity with Blazor basics (components, routing)
- ✓Understanding of HTTP and REST APIs
- 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.
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.
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.
@page directive carefully.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.
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.
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.
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.
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.
The Unauthorized Admin: A Blazor Authorization Bypass
- 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.
Console.WriteLine(state.User.Identity.IsAuthenticated);Console.WriteLine(string.Join(", ", state.User.Claims.Select(c => c.Type)));| File | Command / Code | Purpose |
|---|---|---|
| Startup.cs | services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) | Understanding Authentication and Authorization in Blazor |
| Program.cs | builder.Services.AddDbContext | Setting Up ASP.NET Core Identity with Blazor |
| AdminPage.razor | @page "/admin" | Using AuthorizeView and the [Authorize] Attribute |
| DepartmentRequirement.cs | public class DepartmentRequirement : IAuthorizationRequirement | Implementing Custom Authorization Policies |
| JwtAuthenticationStateProvider.cs | public class JwtAuthenticationStateProvider : AuthenticationStateProvider | Blazor WebAssembly JWT Authentication |
| WeatherForecastController.cs | [ApiController] | Protecting API Endpoints and Server-Side Validation |
| Logout.razor | @inject IJwtAuthenticationStateProvider AuthStateProvider | Handling Authentication State Changes and Logout |
Key takeaways
Common mistakes to avoid
3 patternsRelying 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 Questions on This Topic
Explain the difference between authentication and authorization in Blazor.
Frequently Asked Questions
20+ years shipping production .NET services in enterprise systems. Drawn from code that ran under real load.
That's ASP.NET. Mark it forged?
3 min read · try the examples if you haven't