skip to content

AuthorizeView & Auth State

Components read the user from AuthenticationStateProvider and a cascading Task<AuthenticationState>, gating UI with AuthorizeView and [Authorize]. Interviewers probe why client checks are UI only.

on this pageshow

explore

questions

5

In Blazor, how does AuthorizeView decide what to render, and what do its Roles, Policy and NotAuthorized parameters do?

level: juniorimportance: must knowfreq 60%

answer

  1. needs a cascading Task<AuthenticationState>
  2. no Roles or Policy: default policy
  3. Roles is a comma list, any one
  4. Roles plus Policy: both must pass
  5. hides markup, secures nothing

basics

~20 s

AuthorizeView awaits the cascading authentication state and runs the user through IAuthorizationService. It renders its child content when authorized and NotAuthorized otherwise; Roles accepts any listed role, Policy names a registered policy, and with neither it just requires a signed-in user.

solid answer

~40 s

`AuthorizeView` reads the cascading `Task<AuthenticationState>` (supplied by `AddCascadingAuthenticationState()`), then calls `IAuthorizationService.AuthorizeAsync` with a policy built from its parameters. With no `Roles` or `Policy` it uses the default policy, which only requires an authenticated user. `Roles="Captain, Coach"` passes if the user has any one of them; `Policy="ActiveMembership"` names a policy registered with `AddAuthorization`; if both are set, both must pass. Content goes in the child content or `<Authorized>` (not both), the fallback in `<NotAuthorized>`, and `<Authorizing>` shows while the state task is pending. Both fragments receive `context`, an `AuthenticationState`, so `@context.User` is available. It only decides what markup renders: the page and the handlers behind a hidden button still need their own checks.

code

razor · 10 lines
razor
<AuthorizeView Roles="Captain">
    <p>Captain tools for @context.User.Identity?.Name</p>
    <AuthorizeView Policy="ActiveMembership" Context="membership">
        <button @onclick="OpenRegattaEntries">Enter regatta</button>
    </AuthorizeView>
</AuthorizeView>

@code {
    private void OpenRegattaEntries() { /* the service re-checks the user */ }
}

go deeper

for a junior

Recall the Authorized and NotAuthorized fragments, the context variable, that Roles means any listed role, and that no Roles or Policy means signed-in users only.

for a middle

Explain the cascading Task<AuthenticationState>, the IAuthorizationService call, how Roles and Policy combine, and why setting both ChildContent and Authorized throws.

for a senior

Show you treat AuthorizeView as presentation only and put enforcement on pages, services and web APIs, especially when components run in WebAssembly.

for a principal

Discuss how a team keeps UI visibility rules and server policies from drifting apart, for example by naming every check as a shared policy.

## What `AuthorizeView` is `AuthorizeView` is a built-in component in `Microsoft.AspNetCore.Components.Authorization`. It shows one piece of UI to users who pass an authorization check and, optionally, another piece to users who do not. A rowing-club membership portal uses it to show the **Crew roster** and **Boat bookings** menu items only to captains and coaches, and a **Join the club** link to everyone else. ```razor <AuthorizeView Roles="Captain, Coach"> <Authorized> <NavLink href="admin/crews">Crew roster</NavLink> <NavLink href="admin/boats">Boat bookings</NavLink> </Authorized> <NotAuthorized> <NavLink href="join">Join the club</NavLink> </NotAuthorized> </AuthorizeView> ``` ## How it decides Every time its parameters are set, the component: 1. reads a cascading parameter of type `Task<AuthenticationState>`; if none is cascaded it throws an `InvalidOperationException` ("Authorization requires a cascading parameter of type Task<AuthenticationState>..."); 2. shows the `Authorizing` content while it awaits that task; 3. builds a policy from `Roles` and `Policy` and calls `IAuthorizationService.AuthorizeAsync(user, Resource, policy)`, the same authorization engine the server uses for endpoints; 4. renders the authorized content or `NotAuthorized`. The cascading value usually comes from `builder.Services.AddCascadingAuthenticationState()` in `Program.cs`, which the Blazor Web App template calls when authentication is enabled. ## Its parameters | Parameter | Meaning | |---|---| | `ChildContent` or `Authorized` | content for authorized users; the two are synonyms and setting both throws | | `NotAuthorized` | content for everyone else | | `Authorizing` | content while the authentication state task is still running | | `Roles` | comma-separated role names; one matching role is enough | | `Policy` | the name of one registered authorization policy | | `Resource` | an object passed to `AuthorizeAsync` for resource-based checks | Rules worth knowing: - **Neither `Roles` nor `Policy`:** the **default policy** applies, which by default authorizes any signed-in user and rejects anonymous ones. - **Both `Roles` and `Policy`:** the user must satisfy both. - **All of several roles:** nest one `AuthorizeView` inside another and give the inner one a different `Context` name to avoid a clash with the outer `context`. - **Role names** are compared as ordinary strings, typically case-sensitive; policy names are looked up case-insensitively. - **`context`** is the `AuthenticationState`, so `@context.User.Identity?.Name` greets the member. Defining what a policy such as `ActiveMembership` requires belongs to the server's authorization setup; `AuthorizeView` only refers to it by name. ## Why it is UI only `AuthorizeView` changes the rendered output. It does not protect anything the markup points to: - **A hidden `NavLink`** does not stop a member typing `/admin/boats` into the address bar. The page itself needs `@attribute [Authorize(Roles = "Captain")]`. - **A hidden button** does not protect its handler. Code elsewhere can call the same method, so the service that cancels a boat booking checks the user too. - **With WebAssembly interactivity** the component code runs in the browser and can be modified by the user. Content and actions that matter must come from a web API that authorizes every request on the server. - **With Interactive Server** the handler runs on the server, but the same rule holds: authorize in the operation, not only in the markup. ## Where it works `AuthorizeView` works in every render mode. Under static server-side rendering it evaluates once per request, so the menu above is correct in the HTML the server sends. When interactive, the component re-evaluates whenever the cascading authentication state changes, for example after a revalidating provider signs the user out. `Authorizing` content is rarely visible in server-side rendering because the state is known immediately; it matters when a client-side provider has to fetch the user asynchronously. ## Mistakes that come up - **Setting both `ChildContent` and `<Authorized>`.** Markup placed directly inside the component is `ChildContent`; adding an `<Authorized>` element as well throws an `InvalidOperationException` ("Do not specify both 'Authorized' and 'ChildContent'"). - **Nesting without renaming `context`.** Two nested `AuthorizeView` components both expose `context`; give the inner one `Context="inner"` to avoid the name collision. - **Role spelling.** `Roles="captain"` does not match a `Captain` role claim when the comparison is case-sensitive, which is the usual case. - **A policy registered only on the server.** Components running in WebAssembly evaluate with the browser's own authorization services (`AddAuthorizationCore()` in the `.Client` project), so a `Policy` name missing there throws an `InvalidOperationException` ("The AuthorizationPolicy named: '...' was not found."). ## Interview summary Say what it renders, how roles and policies combine, where the state comes from, and, unprompted, that it is a display tool and not an access-control boundary.

  • How do you require both the Captain and Coach roles with AuthorizeView?
    `Roles="Captain, Coach"` accepts either role. To require both, nest `<AuthorizeView Roles="Coach" Context="inner">` inside `<AuthorizeView Roles="Captain">`, or define a policy that requires both roles and pass its name to `Policy`.
  • The admin menu items are hidden for ordinary members. Is the admin page protected?
    No. `AuthorizeView` only removes markup. A member can still type the URL, so the routable page needs `@attribute [Authorize(Roles = "Captain")]`, and the services or web APIs it calls must authorize the operation on the server.
  • What does the Authorizing fragment show in a server-rendered Blazor Web App?
    Usually nothing visible: the server knows the user as soon as the request or circuit starts, so the state task completes at once. `Authorizing` matters when a client-side `AuthenticationStateProvider` fetches the user asynchronously.

  • Roles="Captain, Coach" requires the user to hold both roles
  • Without Roles or Policy, AuthorizeView shows its content to anonymous users
  • Hiding a button with AuthorizeView prevents its handler from being called
  • AuthorizeView reads HttpContext.User directly, so it needs no cascading state
  • Removing a NavLink with AuthorizeView protects the page it links to
open as a page

In a Blazor Web App, what does @attribute [Authorize] on a page enforce, and when does AuthorizeRouteView's NotAuthorized content actually render?

level: middleimportance: must knowfreq 52%

basics

~20 s

[Authorize] on a routable page is enforced twice: by the authorization middleware when the page is requested from the server, and by AuthorizeRouteView during interactive routing. NotAuthorized renders only in the second case; server requests get a challenge or forbid instead.

open as a page

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%

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.

open as a page

In an Interactive Server Blazor app, why can a member whose Captain role was revoked keep seeing admin UI, and how does RevalidatingServerAuthenticationStateProvider address it?

level: seniorimportance: should knowfreq 34%

basics

~20 s

A circuit keeps the user from the connection that started it, and in-circuit navigation sends no cookies, so a revoked role lingers. RevalidatingServerAuthenticationStateProvider re-checks the user every RevalidationInterval and swaps in an anonymous user when validation fails.

open as a page

In a Blazor Web App with WebAssembly interactivity, what do AddAuthenticationStateSerialization and AddAuthenticationStateDeserialization do, and what are their limits?

level: seniorimportance: should knowfreq 36%

basics

~20 s

AddAuthenticationStateSerialization persists the server's authentication state into the prerendered page; AddAuthenticationStateDeserialization registers a client AuthenticationStateProvider that reads it back. The copy holds name and role claims by default, never changes until a full reload, and authenticates nothing.

open as a page