Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 41 ยท JS Interop and Auth

Authentication and Authorization in Blazor

Learn how Blazor knows who the user is, how AuthenticationState, AuthorizeView, the Authorize attribute and cascading state work, and how claims drive what users see.

Authentication answers "who are you?" and authorization answers "what may you do?". Blazor does not invent its own login system. It reads the user's identity from the host (ASP.NET Core cookies, ASP.NET Core Identity, OpenID Connect providers, a token in WebAssembly) and exposes it to components as a standard .NET ClaimsPrincipal. Your job in components is to ask the framework about that identity and shape the UI accordingly.

The real sign-in flow needs a running ASP.NET Core host, a user store and cookies, none of which exist in this tutorial's runner. So the Razor and Program.cs snippets are real and read-only, and the runnable examples are stand-ins: they use the genuine System.Security.Claims types, which are plain .NET, to show exactly what Blazor's components see.

The mental model

flowchart LR
    H["Host<br/>(cookie, Identity, OIDC, token)"] --> P["AuthenticationStateProvider"]
    P --> S["AuthenticationState<br/>User = ClaimsPrincipal"]
    S --> A["AuthorizeView<br/>[Authorize]<br/>CascadingAuthenticationState"]
    A --> U["What the user sees"]

The host proves identity; the provider turns it into a ClaimsPrincipal; components read it.

A ClaimsPrincipal holds one or more identities, and each identity holds claims: small name/value facts such as name, email, role or subscription=pro. User.Identity.IsAuthenticated is true when the identity was created with an authentication type.

Getting the state into components

In a Blazor Web App, a cascading authentication state is registered for you:

C#
builder.Services.AddCascadingAuthenticationState();

Components can then receive it as a cascading parameter, as in Component State and Cascading Values:

RAZOR
@code {
    [CascadingParameter]
    private Task<AuthenticationState>? AuthState { get; set; }

    private string greeting = "Hello, stranger";

    protected override async Task OnInitializedAsync()
    {
        if (AuthState is null) return;
        var user = (await AuthState).User;
        if (user.Identity?.IsAuthenticated == true)
        {
            greeting = $"Hello, {user.Identity.Name}";
        }
    }
}

The state is a Task<AuthenticationState> because on the client it may have to be fetched. Await it; do not block on .Result.

AuthorizeView: conditional UI

AuthorizeView shows different markup depending on the user. It reads the cascading state itself:

RAZOR
<AuthorizeView>
    <Authorized>
        <p>Signed in as <strong>@context.User.Identity?.Name</strong></p>
        <a href="/logout">Sign out</a>
    </Authorized>
    <NotAuthorized>
        <a href="/login">Sign in</a>
    </NotAuthorized>
    <Authorizing>
        <p>Checking your session...</p>
    </Authorizing>
</AuthorizeView>

You can restrict by role or policy, too: <AuthorizeView Roles="Admin"> or <AuthorizeView Policy="CanEditPosts">. The next lesson, Policies, Roles and Claims, covers those in depth.

Hiding a button is not security. In WebAssembly, anyone can read the downloaded code and call your API directly. Always enforce rules on the server, in the API or the server-side logic, and treat AuthorizeView as a UX convenience.

Protecting whole pages

The [Authorize] attribute on a routable component (or @attribute [Authorize]) requires a signed-in user:

RAZOR
@page "/account"
@attribute [Authorize]

<h1>My account</h1>

For [Authorize] to take effect, the router must use AuthorizeRouteView (the default templates configure it):

RAZOR
<Router AppAssembly="typeof(Program).Assembly">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)">
            <NotAuthorized>
                <p>You must sign in to see this page.</p>
            </NotAuthorized>
        </AuthorizeRouteView>
    </Found>
</Router>

[Authorize] only works on routable components (those with @page). Putting it on a child component does nothing; use AuthorizeView there. [AllowAnonymous] opts a page out when a whole folder is protected.

What the component sees, runnable

The following program builds a ClaimsPrincipal the same way a cookie handler would and then runs the checks that AuthorizeView and [Authorize] perform. The AuthorizeView function is a stand-in written for this lesson.

C# Stand-in: ClaimsPrincipal and AuthorizeView logic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Note that IsAuthenticated is false for an identity created without an authentication type. That is how anonymous visitors look: a principal with an empty identity, never null.

A custom AuthenticationStateProvider

For a demo, a test or a custom token scheme you can supply your own provider. It returns the state components should see:

C#
public class FakeAuthProvider : AuthenticationStateProvider
{
    public override Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        var identity = new ClaimsIdentity(
            [new Claim(ClaimTypes.Name, "demo-user"), new Claim(ClaimTypes.Role, "Admin")],
            "Fake");
        return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(identity)));
    }
}

builder.Services.AddScoped<AuthenticationStateProvider, FakeAuthProvider>();

When the identity changes at runtime (login, logout), the provider raises NotifyAuthenticationStateChanged(Task<AuthenticationState>) and every AuthorizeView re-renders. This stand-in shows the notify pattern with plain events:

C# Stand-in: provider that notifies when the user changes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Where the login really happens

  • Blazor Web App / Server: ASP.NET Core handles login with cookies (often via ASP.NET Core Identity). The circuit sees the user that opened the connection. Login pages are normal server-rendered pages, because a cookie must be set in an HTTP response, which a live SignalR circuit cannot do.
  • Blazor WebAssembly: the app usually signs in against an identity provider with OpenID Connect and gets tokens. An HttpClient message handler attaches the access token to API calls (see Calling APIs from Blazor with HttpClient). The browser holds tokens, so keep their lifetime short.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type represents the signed-in user that Blazor components read?

    The AuthenticationStateProvider produces an AuthenticationState whose User is a ClaimsPrincipal.
  2. 2. Where does the [Authorize] attribute work?

    The router checks it. For parts of a page use AuthorizeView.
  3. 3. Why is hiding a button with AuthorizeView not enough for security?

    UI hiding is a convenience. Real enforcement belongs on the server or API.
  4. 4. How does an anonymous visitor appear to a component?

    The user is never null; IsAuthenticated is false.

Summary

  • Blazor reads identity from the host as a ClaimsPrincipal inside AuthenticationState.
  • Register AddCascadingAuthenticationState() and use AuthorizeView for conditional markup.
  • [Authorize] protects routable pages via AuthorizeRouteView.
  • A custom AuthenticationStateProvider supplies the user and notifies components of changes.
  • UI checks are for experience; enforce permissions on the server.

Next: Policies, Roles and Claims