Learn Blazor · 14/15

Authentication & Authorization

7 min read

Module 14: Authentication & Authorization in Blazor

Welcome to the VIP section of application development. 🛡️

Up until now, your Blazor app has been like an open house party—anyone with the URL could walk in, eat your pizza, and maybe even rearrange your furniture. Now, we are going to hire a bouncer and install some locks.

In this guide, we will implement industry-standard security patterns. We won't cover obscure security algorithms that only NASA uses. We will focus on what you need to build a secure Line-of-Business (LOB) application today.


The Big Picture: AuthN vs. AuthZ

Before we touch code, let's clear up the confusion between these two acronyms. They look similar, but mixing them up is like confusing your car keys with your house keys.

1. Authentication (AuthN):

  • Definition: The process of verifying the identity of a user.
  • The Question: "Who are you?"
  • Real World: Showing your Passport at the airport border control. They verify you are indeed "John Doe."

2. Authorization (AuthZ):

  • Definition: The process of determining what an authenticated user is allowed to do.
  • The Question: "What are you allowed to do?"
  • Real World: Your Boarding Pass. Just because you are John Doe (Authenticated) doesn't mean you can sit in the First Class cockpit (Authorized).

1. Understanding the AuthenticationStateProvider

The Problem

In a traditional web app (like MVC), every time you click a link, the browser sends a cookie to the server, and the server says, "Ah, yes, this is User 42."

But Blazor (especially WebAssembly) is a Single Page Application (SPA). Once loaded, you might stay on the same page for hours. The app needs a way to track your identity in memory without asking the server every 5 milliseconds. If the UI doesn't know you are logged in, it can't hide the "Login" button.

The Solution: AuthenticationStateProvider

Blazor uses a specialized service called the AuthenticationStateProvider. Think of this service as the Global Town Crier for your app.

  • It holds the current user's data (ClaimsPrincipal).
  • It notifies the rest of the app when the user logs in or logs out.

Under the hood, this is an abstract class. You don't usually use the default one for custom APIs; you create a class that inherits from it.

The Core Mechanism:
When your app needs to know who is online, it calls GetAuthenticationStateAsync().

csharp
// Concept code - Under the hood
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
    // 1. Check local storage for a token
    // 2. If token exists and is valid, return "User is Logged In"
    // 3. If not, return "User is Anonymous"
}

Industry Fact: In 99% of professional Blazor projects connecting to microservices or external APIs, you will write a CustomAuthenticationStateProvider. The default one is mostly for server-side Razor pages or basic demos.


2. Protecting Routes and Pages with the [Authorize] Attribute

The Problem

You have a page /admin/delete-database. You don't want a curious intern stumbling upon this URL and thinking, "I wonder what this button does?" 💥

The Solution: [Authorize]

This is a declarative attribute you slap on top of your Razor components. It acts like a biometric scanner on a door. If the AuthenticationStateProvider says the user is "Anonymous," Blazor will refuse to render the page and (usually) redirect them to login.

Setup Requirement (The Boilerplate):
Before attributes work, you must wrap your Router in App.razor with CascadingAuthenticationState. If you forget this, the [Authorize] attribute will be ignored, and your security will be non-existent.

File: App.razor

razor
<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    <!-- What to show if they get caught sneaking in -->
                    <h1>Access Denied! 🛑</h1>
                    <p>You need to log in to see this.</p>
                </NotAuthorized>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <PageTitle>Not found</PageTitle>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

Protecting a Page:
Now, open any page (e.g., Dashboard.razor) and add the attribute.

razor
@page "/dashboard"
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]

<h3>Top Secret Dashboard</h3>
<p>Only logged-in users see this.</p>

Pro Tip: Add @using Microsoft.AspNetCore.Authorization to your _Imports.razor file. Otherwise, you have to type that using statement on every single protected page, which is annoying enough to make you reconsider your career choices.


3. Conditional UI Rendering with the AuthorizeView Component

The Problem

You have a navigation bar.

  1. When logged out, it should show "Register" and "Login."
  2. When logged in, it should show "Profile" and "Logout."

Also, inside the dashboard, only the Manager should see the "Edit Salary" button. The [Authorize] attribute protects the whole page, but how do we protect parts of a page?

The Solution: <AuthorizeView>

This component exposes the current authentication state to its children. It has three main child buckets:

  1. <Authorized>: Shows content to logged-in users.
  2. <NotAuthorized>: Shows content to anonymous users.
  3. <Authorizing>: (Optional) Shows while the app is checking (e.g., "Loading...").

Example: The Navigation Bar

razor
<nav>
    <a href="/">Home</a>
    
    <AuthorizeView>
        <Authorized>
            <!-- User is logged in -->
            <span>Hello, @context.User.Identity.Name! 👋</span>
            <button @onclick="Logout">Logout</button>
        </Authorized>
        <NotAuthorized>
            <!-- User is NOT logged in -->
            <a href="login">Login</a>
            <a href="register">Register</a>
        </NotAuthorized>
    </AuthorizeView>
</nav>

Example: Role-Based Authorization
Imagine running a pizza shop (the system). You have customers and chefs. A customer can view the menu, but only a chef can change the ingredients.

razor
<AuthorizeView Roles="Admin, Chef">
    <button class="btn btn-danger">Update Pizza Recipe 🍕</button>
</AuthorizeView>

If the user's claims do not include the role "Admin" or "Chef," the button simply doesn't exist in the DOM. It’s not just hidden with CSS; it’s physically not there.


4. Integrating with JWT and External Identity Providers

The Problem

The AuthenticationStateProvider needs to know how to determine if you are logged in. In modern web development, we don't hold state on the server (Stateless). We use Tokens.

Specifically, JWT (JSON Web Tokens).

A JWT is like a digital wristband given to you by an amusement park (the API).

  1. You log in with a username/password.
  2. The API checks the DB. If correct, it hands you a JWT (wristband).
  3. You store that JWT (put on the wristband).
  4. Every time you want to ride a rollercoaster (request data), you show the wristband.

The Solution: Custom AuthenticationStateProvider

We need to teach Blazor how to look for this JWT, read it, and tell the app "We are logged in."

Step 1: The Logic Flow

  1. Login: User posts credentials to API -> API returns JWT string -> Blazor saves JWT in LocalStorage.
  2. Notification: Blazor reads LocalStorage -> Decodes JWT -> Notifies Task<AuthenticationState>.

Step 2: The Implementation (Simplified Industry Standard)

This is the code you will actually write in a real job.

csharp
using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;
using System.Net.Http.Headers;

public class CustomAuthProvider : AuthenticationStateProvider
{
    private readonly ILocalStorageService _localStorage;
    private readonly HttpClient _http;

    public CustomAuthProvider(ILocalStorageService localStorage, HttpClient http)
    {
        _localStorage = localStorage;
        _http = http;
    }

    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        // 1. Try to get the token from browser storage
        string token = await _localStorage.GetItemAsync<string>("authToken");

        var identity = new ClaimsIdentity(); // Empty = Anonymous

        if (!string.IsNullOrEmpty(token))
        {
            // 2. If token exists, parse it to get user info (Name, Roles, etc.)
            // Note: ParseClaimsFromJwt is a helper method you'd write to decode Base64
            identity = new ClaimsIdentity(ParseClaimsFromJwt(token), "jwt");
            
            // 3. Attach token to outgoing HTTP requests automatically
            _http.DefaultRequestHeaders.Authorization = 
                new AuthenticationHeaderValue("Bearer", token);
        }

        var user = new ClaimsPrincipal(identity);
        return new AuthenticationState(user);
    }

    // Call this method after the user successfully logs in
    public void NotifyUserLoggedIn(string token)
    {
        var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(ParseClaimsFromJwt(token), "jwt"));
        var authState = Task.FromResult(new AuthenticationState(authenticatedUser));
        
        // This magic method triggers the UI update!
        NotifyAuthenticationStateChanged(authState);
    }

    // Call this when they log out
    public void NotifyUserLogout()
    {
        var anonymousUser = new ClaimsPrincipal(new ClaimsIdentity());
        var authState = Task.FromResult(new AuthenticationState(anonymousUser));
        NotifyAuthenticationStateChanged(authState);
    }
}

Why is this cool?
Because you control the flow. Whether the token comes from Azure AD, Auth0, or your own custom .NET WebAPI, this provider acts as the bridge (Adapter Pattern) between your token and Blazor's UI.


🧠 Fun Fact

In the early days of the web, authentication was often handled by "Basic Auth," which literally sent your password in the header on every request. That’s like shouting your ATM PIN code every time you buy a stick of gum. Thank goodness for JWTs and OAuth flows!

Summary checklist

  1. Wrap app in CascadingAuthenticationState.
  2. Implement CustomAuthenticationStateProvider.
  3. Use [Authorize] for whole pages.
  4. Use <AuthorizeView> for buttons/text.
  5. Don't store sensitive secrets in Blazor WebAssembly code (the user can download your DLLs!).

🔗 References & Extra Reading

Challenge

You are tasked with implementing the core security components for a Blazor WebAssembly application. Your goal is to create a custom authentication provider that can simulate parsing a token and a secure Razor component that displays content based on user roles.

Part 1: Custom Authentication Provider

Create a C# class named JwtAuthStateProvider that inherits from AuthenticationStateProvider.

  1. Override GetAuthenticationStateAsync: This method should simulate reading a token from a source (for this exercise, you'll use a hardcoded string variable).
    • If the token is "eyAdminToken...", create a ClaimsPrincipal for a user named [email protected] who has the role of Admin.
    • If the token is "eyUserToken...", create a ClaimsPrincipal for a user named [email protected] but with no specific roles.
    • If the token is null or any other value, return an AuthenticationState for an anonymous user.
  2. Implement Notification Methods: Create two public methods, MarkUserAsAuthenticated() and MarkUserAsLoggedOut(). These methods will be responsible for notifying the Blazor application about authentication state changes by invoking the base NotifyAuthenticationStateChanged method.

Part 2: Secure Razor Component

Create a Razor component named AdminPortal.razor.

  1. Page-Level Security: Apply an attribute to the component to ensure that only authenticated users can view it.
  2. Role-Based UI: Use the AuthorizeView component to render different content within the page.
    • Display an <h3> element with the text "Management Dashboard" only to users who have the Admin role.
    • Inside the Authorized context, but outside the role-specific view, display a <p> tag that says "Welcome, @context.User.Identity.Name".
    • For unauthenticated users, display a <p> tag with the text "You are not authorized to see this content.".

Expected result

Your final code should consist of two completed parts: a C# class and a Razor component.

JwtAuthStateProvider.cs

  • The class correctly inherits from AuthenticationStateProvider.
  • The GetAuthenticationStateAsync method is overridden and returns a Task<AuthenticationState>.
  • Inside GetAuthenticationStateAsync, the logic correctly creates a ClaimsPrincipal with a ClaimsIdentity.
  • The identity for the admin user must include a Claim of type ClaimTypes.Role with the value "Admin".
  • The methods MarkUserAsAuthenticated and MarkUserAsLoggedOut correctly call NotifyAuthenticationStateChanged with the result of GetAuthenticationStateAsync().

AdminPortal.razor

  • The @page directive is followed by the [Authorize] attribute.
  • The component contains an <AuthorizeView> component.
  • Inside the <AuthorizeView>, there is an <Authorized> section that displays the welcome message using the context variable.
  • Nested inside the <Authorized> section is another <AuthorizeView> with its Roles parameter set to "Admin" containing the <h3> management dashboard title.
  • The component includes a <NotAuthorized> section containing the specified paragraph for unauthorized users.
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.