skip to content

In a Blazor component, how should code read the current user: a cascading Task<AuthenticationState>, AuthenticationStateProvider, or HttpContext, and what does AddCascadingAuthenticationState register?

level: middleimportance: should knowfreq 45%

answer

  1. [CascadingParameter] Task<AuthenticationState>
  2. a root-level cascading value since .NET 8
  3. AuthenticationStateChanged drives updates
  4. HttpContext only during static SSR
  5. IAuthorizationService for policy checks

basics

~10 s

Use a [CascadingParameter] Task<AuthenticationState>; AddCascadingAuthenticationState registers it as a root-level cascading value fed by AuthenticationStateProvider and refreshed on its changes. Inject the provider only in services, and use HttpContext only during static SSR.

solid answer

~40 s

Since .NET 8, `builder.Services.AddCascadingAuthenticationState()` registers a root-level cascading value of type `Task<AuthenticationState>`. It is created from `AuthenticationStateProvider.GetAuthenticationStateAsync` and is not fixed: it subscribes to `AuthenticationStateChanged` and notifies components when the user changes. Being a DI-based cascading value, it reaches interactive components across render-mode boundaries, which the old `<CascadingAuthenticationState>` wrapper cannot. In a component, declare `[CascadingParameter] private Task<AuthenticationState>? AuthState { get; set; }`, await it, and read `User`. For policy checks in code, pass that user to `IAuthorizationService.AuthorizeAsync`. Injecting `AuthenticationStateProvider` works too but gives no automatic re-render, so subscribe to the event yourself; on the server its `GetAuthenticationStateAsync` throws outside a component's DI scope. `HttpContext` is valid only during static SSR; interactive components should not use `IHttpContextAccessor`.

code

csharp · 10 lines
csharp
// Program.cs of a Blazor Web App (.NET 10)
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

builder.Services.AddAuthentication()
    .AddCookie();
builder.Services.AddAuthorization();

// One root-level cascading Task<AuthenticationState> for every render mode.
builder.Services.AddCascadingAuthenticationState();

go deeper

for a junior

Recall the [CascadingParameter] Task<AuthenticationState> pattern, awaiting it to get User, and the AddCascadingAuthenticationState line in Program.cs.

for a middle

Explain how the cascading value subscribes to AuthenticationStateChanged, when to inject the provider instead, and why HttpContext is a static SSR tool.

for a senior

Show you can diagnose a stale user in interactive islands, providers called outside a component scope, and IHttpContextAccessor misuse in circuits.

for a principal

Discuss how shared services across render modes should receive identity, and the rule for passing user identity into background work explicitly.

## The pieces Three types carry the signed-in user in Blazor, all in `Microsoft.AspNetCore.Components.Authorization`: - **`AuthenticationState`** wraps a `ClaimsPrincipal` in its `User` property. - **`AuthenticationStateProvider`** is the DI service that produces it: `Task<AuthenticationState> GetAuthenticationStateAsync()` plus an `AuthenticationStateChanged` event raised through the protected `NotifyAuthenticationStateChanged` method. - **A cascading `Task<AuthenticationState>`** is how components receive it without injecting anything. On the server, `AddRazorComponents()` registers `ServerAuthenticationStateProvider`, which takes `HttpContext.User` during server rendering and the circuit's user when interactive. Client-side apps register their own provider. ## What `AddCascadingAuthenticationState` registers `AddCascadingAuthenticationState()` calls `AddCascadingValue<Task<AuthenticationState>>` with a source that: 1. asks the `AuthenticationStateProvider` for the current state; 2. is **not fixed**, so it subscribes to `AuthenticationStateChanged`; 3. pushes the new task to every subscribed component when the provider reports a change, which re-renders `AuthorizeView`, `AuthorizeRouteView` and your own components. In .NET 7 and earlier, apps wrapped the router in a `<CascadingAuthenticationState>` component instead. In a Blazor Web App that wrapper has a real limitation: **cascading values from components do not cross render-mode boundaries**, so an `InteractiveServer` island inside a static page would not receive the state. A root-level cascading value is a DI service, so every component gets it, whatever its render mode. The component still exists, and `AuthorizeRouteView` uses it internally when nothing is cascaded, but new code registers the service. ## Reading the user in a component The rowing club's **My bookings** page shows the member's name and checks a policy before offering cancellation: ```razor @inject IAuthorizationService AuthorizationService @code { [CascadingParameter] private Task<AuthenticationState>? AuthState { get; set; } private bool canCancel; protected override async Task OnParametersSetAsync() { if (AuthState is null) return; var user = (await AuthState).User; var result = await AuthorizationService.AuthorizeAsync(user, "ActiveMembership"); canCancel = result.Succeeded; } } ``` Awaiting the task in `OnParametersSetAsync` rather than only in `OnInitializedAsync` lets the component pick up a changed task when the provider notifies. ## Choosing a source | Source | Use it for | Watch out | |---|---|---| | `[CascadingParameter] Task<AuthenticationState>` | components | the property may be `null` if nothing cascades it | | `AuthenticationStateProvider` injected | services used by components, custom providers | no automatic re-render; subscribe to `AuthenticationStateChanged` and unsubscribe on dispose | | `HttpContext` (cascading parameter during static SSR) | statically rendered pages that need headers or cookies | it is `null` in interactive components | | `IHttpContextAccessor` | static SSR and server code that is guaranteed to run in a request | avoid in interactive rendering; a circuit is not an HTTP request | Two failure modes come up in interviews: - **Calling the server provider outside a component scope.** `ServerAuthenticationStateProvider.GetAuthenticationStateAsync` throws an `InvalidOperationException` ("Do not call GetAuthenticationStateAsync outside of the DI scope for a Razor component") when used from middleware, a Minimal API handler or a hosted service. Those places have their own user: `HttpContext.User`, or none. - **Assuming `HttpContext` follows the circuit.** An Interactive Server component runs over a long-lived connection; the HTTP request that started it is long gone, so reading the current user from it gives stale or missing data. ## Custom providers Apps with their own sign-in flow sometimes write a provider: 1. derive from `AuthenticationStateProvider` and implement `GetAuthenticationStateAsync`; 2. after a sign-in or sign-out, call the protected `NotifyAuthenticationStateChanged(Task.FromResult(newState))`; 3. register it with `builder.Services.AddScoped<AuthenticationStateProvider, ClubAuthStateProvider>()`. Step 2 is what makes `AuthorizeView` update: the cascading value registered by `AddCascadingAuthenticationState()` listens to exactly that event. A provider that changes its internal state without notifying leaves every component showing the old user until something else re-renders them. ## Why `Task` and not `AuthenticationState` The value is a task because some providers, notably client-side ones, determine the user asynchronously. Components await it, and `AuthorizeView` shows its `Authorizing` content while it is pending. On the server the task is usually already complete. ## Summary Register `AddCascadingAuthenticationState()` once, read the user from the cascading task in components, inject the provider only where components cannot reach (and subscribe to its event), and treat `HttpContext` as a static-SSR-only tool.

  • A hosted service calls the injected AuthenticationStateProvider and throws. Why?
    On the server, `ServerAuthenticationStateProvider` only receives a user when a Razor component's scope is set up, from `HttpContext.User` or the circuit. In a hosted service's own scope nothing sets it, so `GetAuthenticationStateAsync` throws an `InvalidOperationException`. Background work has no current user; pass the user's id explicitly.
  • When would you inject AuthenticationStateProvider instead of using the cascading parameter?
    In a scoped service that components use, or when writing a custom provider. The service is not a component, so it cannot receive cascading parameters; it calls `GetAuthenticationStateAsync` and subscribes to `AuthenticationStateChanged` to react to sign-outs, unsubscribing when disposed.

  • AddCascadingAuthenticationState cascades a fixed value read once at startup
  • Injecting AuthenticationStateProvider re-renders the component when the user signs out
  • IHttpContextAccessor gives the current user reliably inside Interactive Server components
  • A <CascadingAuthenticationState> wrapper reaches interactive islands inside a static page
  • GetAuthenticationStateAsync can be called from any middleware or hosted service

Assumes ASP.NET Core 10: AddCascadingAuthenticationState (added in .NET 8) replaces wrapping the Router in <CascadingAuthenticationState>, which .NET 7 and earlier apps used.