In Blazor, how does AuthorizeView decide what to render, and what do its Roles, Policy and NotAuthorized parameters do?
answer
- needs a cascading Task<AuthenticationState>
- no Roles or Policy: default policy
- Roles is a comma list, any one
- Roles plus Policy: both must pass
- hides markup, secures nothing
basics
~20 sAuthorizeView 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<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
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.
Explain the cascading Task<AuthenticationState>, the IAuthorizationService call, how Roles and Policy combine, and why setting both ChildContent and Authorized throws.
Show you treat AuthorizeView as presentation only and put enforcement on pages, services and web APIs, especially when components run in WebAssembly.
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