skip to content

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%

answer

  1. only on routable @page components
  2. page attributes become endpoint metadata
  3. static SSR: the middleware challenges
  4. interactive routing: AuthorizeRouteView checks
  5. default text "Not authorized"

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.

solid answer

~40 s

`@attribute [Authorize(Roles = "Captain")]` works only on `@page` components reached through the router; child components are not checked. `MapRazorComponents` copies a page's attributes into its endpoint metadata, so a request rendered on the server (static SSR or the prerender of an interactive page) is authorized by the authorization middleware: an anonymous user gets the scheme's challenge, typically a redirect to the cookie login path, and a signed-in user without the role gets a forbid. The router's `NotAuthorized` content never runs there. Once routing is interactive, `AuthorizeRouteView` in `Routes.razor` reads the page's `[Authorize]` data, skips pages marked `[AllowAnonymous]`, and renders `NotAuthorized` (default text "Not authorized") or `Authorizing` inside `DefaultLayout`. The template puts a `RedirectToLogin` component there. An `[Authorize]` that names `AuthenticationSchemes` throws `NotSupportedException` in components.

code

razor · 9 lines
razor
@page "/admin/boats"
@attribute [Authorize(Roles = "Captain")]
@inject BoatBookingService Bookings

<h1>Boat bookings</h1>

@code {
    // BoatBookingService also checks the user before changing a booking.
}

go deeper

for a junior

Recall that @attribute [Authorize] protects routable pages, that Roles and Policy work as on controllers, and that Routes.razor uses AuthorizeRouteView.

for a middle

Explain the two enforcement points, endpoint metadata checked by the middleware versus AuthorizeRouteView during interactive routing, and when NotAuthorized appears.

for a senior

Show you can diagnose pages reachable after an in-app click, login loops between NotAuthorized and the cookie paths, and the NotSupportedException from schemes.

for a principal

Discuss a consistent unauthorized experience across server and interactive navigation, and where the team draws the line between page and data protection.

## The attribute on a page In a Razor component, `@attribute [Authorize]` adds ASP.NET Core's `AuthorizeAttribute` to the generated class. It takes the same forms as on controllers: `[Authorize]` for any signed-in user, `[Authorize(Roles = "Captain")]`, or `[Authorize(Policy = "ActiveMembership")]`. In the rowing-club portal, the boat-booking admin page is declared like this: ```razor @page "/admin/boats" @attribute [Authorize(Roles = "Captain")] <h1>Boat bookings</h1> ``` The attribute is honoured **only on routable components**, the ones with `@page`. Authorization is part of routing, so putting `[Authorize]` on a child component such as a `CrewEditor` does nothing; use `AuthorizeView` for parts of a page. ## Enforcement point 1: the server endpoint `MapRazorComponents<App>()` builds one endpoint per routable component and copies **all of the component's attributes** into the endpoint's metadata. The authorization middleware (`UseAuthorization`, which `WebApplication` adds for you when authorization services are registered) therefore sees `[Authorize]` on every request rendered on the server: - the first request for a page, - every request of a statically rendered site, including enhanced navigations, - the prerender of an interactive page. When the check fails, no component renders at all. The middleware asks the authentication scheme to **challenge** an anonymous user, which for cookie authentication means a redirect to its login path, or to **forbid** a signed-in user who lacks the role. This is why the Blazor docs warn that `<NotAuthorized>` content is never shown when authorization fails during static SSR: the request never reaches the router. ## Enforcement point 2: the interactive router After the app is interactive, a click on a link to `/admin/boats` is routed in the browser or over the circuit, and no HTTP request reaches the middleware. The check then happens in `AuthorizeRouteView`, a subclass of `RouteView` used in place of it in `Routes.razor`: ```razor <Router AppAssembly="typeof(Program).Assembly" NotFoundPage="typeof(Pages.NotFound)"> <Found Context="routeData"> <AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)"> <NotAuthorized> <RedirectToLogin /> </NotAuthorized> </AuthorizeRouteView> </Found> </Router> ``` What it does: 1. reads the page type's attributes (cached per type); `[AllowAnonymous]` on the page skips authorization entirely; 2. combines the `IAuthorizeData` entries into a policy and runs it against the cascading authentication state, like `AuthorizeView`; 3. renders the page when it passes, or `NotAuthorized` / `Authorizing` **inside `DefaultLayout`** when it does not; 4. falls back to the plain text "Not authorized" and "Authorizing..." when those fragments are not supplied; 5. wraps itself in `CascadingAuthenticationState` if no authentication state is cascaded yet. `AuthorizeRouteView` also has a `Resource` parameter, which passes an object such as the route data to resource-based policies. ## Comparing the two | | Server request (static SSR, prerender) | Interactive routing | |---|---|---| | Who checks | authorization middleware | `AuthorizeRouteView` | | Anonymous user | challenge, usually a login redirect | `NotAuthorized` content | | Signed-in, wrong role | forbid, usually the access-denied path | `NotAuthorized` content | | What you configure | the cookie scheme's paths | the `NotAuthorized` fragment | The Blazor Web App template with Individual Accounts covers both: Identity's cookie options send server requests to the login page, and the router's `RedirectToLogin` component calls `NavigateTo("Account/Login?returnUrl=...", forceLoad: true)` for interactive navigations, so the login page is rendered by the server. ## Protecting a whole folder Razor applies directives in an `_Imports.razor` file to every component in that folder and below. The Blazor Web App template uses this for its account-management pages: `Components/Account/Pages/Manage/_Imports.razor` contains `@attribute [Microsoft.AspNetCore.Authorization.Authorize]`, so every page under `Manage` requires a signed-in user without repeating the attribute. The rowing club can do the same for an `Admin` folder with `@attribute [Authorize(Roles = "Captain")]`, and mark the one public page in a protected folder with `@attribute [AllowAnonymous]`. ## Restrictions and traps - **No authentication schemes.** `[Authorize(AuthenticationSchemes = "...")]` makes component authorization throw a `NotSupportedException`: a component already has one user, so choosing a scheme there is meaningless. - **Plain `RouteView` ignores the attribute.** With `RouteView` instead of `AuthorizeRouteView`, interactive navigation renders a protected page to anyone; only server requests are guarded. - **Data still needs protection.** `[Authorize]` controls whether the page renders. A WebAssembly page's data comes from web APIs, which need their own authorization.

  • Why does an [Authorize] page show the cookie login page on a direct visit but the router's NotAuthorized content after an in-app click?
    The direct visit is an HTTP request, so the authorization middleware checks the endpoint metadata and the cookie scheme challenges with a redirect to its login path. The in-app click is interactive routing with no HTTP request, so `AuthorizeRouteView` performs the check and renders `NotAuthorized`.
  • What happens if Routes.razor uses RouteView instead of AuthorizeRouteView?
    Server requests are still protected because the endpoint carries the `[Authorize]` metadata. Interactive navigations are not: `RouteView` renders any page without consulting its attributes, so a member can reach the captain's page by clicking a link once the app is interactive.

  • [Authorize] on a child component hides it from users without the role
  • During static SSR a failed [Authorize] check renders the router's NotAuthorized content
  • RouteView enforces [Authorize] during interactive navigation just like AuthorizeRouteView
  • [Authorize(AuthenticationSchemes = "Cookies")] picks the scheme Blazor components authenticate with
  • [AllowAnonymous] has no effect on routable Razor components