Configure Auth

作者 dotnet0608d8924cd3MIT5.5K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫今天更新

Add authentication and authorization to a Blazor Web App, accounting for the app's render mode. USE WHEN the user needs [Authorize] on pages, AuthorizeView, role or policy-based access, login/logout Identity pages, or AuthenticationStateProvider. Also USE WHEN auth state is null after WebAssembly loads, SignInManager throws in an interactive component, NotAuthorized content never renders in static SSR, or HttpContext.User is null in an interactive component. DO NOT USE for general component authoring (see author-component), for prerendering concerns unrelated to auth (see support-prerendering), or for managing non-auth cascading state (see coordinate-components).

AI 產生的概覽

指導為 Blazor Web App 加入驗證與授權,並考量應用程式的呈現模式。

功能
此技能提供逐步指示,用於將驗證與授權接入 Blazor Web App。內容涵蓋在 Program.cs 中註冊驗證服務、使用 AuthorizeRouteView 設定 App.razor 與 Routes.razor、透過 [Authorize] 與 AuthorizeView 保護頁面、讓 Identity 頁面維持靜態 SSR,以及為 WebAssembly 或 Auto 模式序列化驗證狀態。它也包含呈現模式與驗證的對照表,以及常見錯誤、症狀與修正方式表。
適用情境
當 Blazor 應用程式需要在頁面上使用 [Authorize]、AuthorizeView、以角色或原則為基礎的存取、登入/登出 Identity 頁面或 AuthenticationStateProvider 時使用。它也適用於 WebAssembly 載入後驗證狀態為 null、SignInManager 在互動式元件中擲出例外、NotAuthorized 內容在靜態 SSR 中始終不呈現,或互動式元件中 HttpContext.User 為 null 的情況。
執行需求
不隨附指令碼,僅為指示性內容。它假定存在 Blazor Web App 專案,並在相關情境中使用 ASP.NET Core Identity 與 Entity Framework Core;代理在進行變更前應閱讀工作區根目錄下的 AGENTS.md。

Configure Auth

Step 1 — Read AGENTS.md

Read AGENTS.md at the workspace root for the project's interactivity mode and scope before making changes.

Step 2 — Register auth services in Program.cs

csharp
// Program.cs (server project)builder.Services.AddCascadingAuthenticationState();builder.Services.AddAuthorization();

For ASP.NET Core Identity add the Identity services:

csharp
builder.Services.AddAuthentication(options =>{    options.DefaultScheme = IdentityConstants.ApplicationScheme;    options.DefaultSignInScheme = IdentityConstants.ExternalScheme;}).AddIdentityCookies();
builder.Services.AddIdentityCore<ApplicationUser>()    .AddRoles<IdentityRole>()    .AddEntityFrameworkStores<ApplicationDbContext>()    .AddSignInManager()    .AddDefaultTokenProviders();

Step 3 — Wire App.razor for auth and render mode

The App.razor component must use AuthorizeRouteView and conditionally apply the render mode so that pages excluded from interactive routing render statically.

razor
<!DOCTYPE html><html><head>    <HeadOutlet @rendermode="RenderModeForPage" /></head><body>    <Routes @rendermode="RenderModeForPage" />    <script src="_framework/blazor.web.js"></script></body></html>
@code {    [CascadingParameter]    public HttpContext HttpContext { get; set; } = default!;
    private IComponentRenderMode? RenderModeForPage =>        HttpContext.AcceptsInteractiveRouting()            ? InteractiveServer   // replace with the app's render mode            : null;}

In Routes.razor (or wherever the router lives), use AuthorizeRouteView:

razor
<Router AppAssembly="typeof(Program).Assembly">    <Found Context="routeData">        <AuthorizeRouteView RouteData="routeData"                            DefaultLayout="typeof(Layout.MainLayout)">            <NotAuthorized>                @if (context.User.Identity?.IsAuthenticated != true)                {                    <RedirectToLogin />                }                else                {                    <p>You are not authorized to access this resource.</p>                }            </NotAuthorized>        </AuthorizeRouteView>        <FocusOnNavigate RouteData="routeData" Selector="h1" />    </Found></Router>

Step 4 — Protect pages and components

[Authorize] attribute on pages

razor
@page "/admin"@attribute [Authorize]

With roles or policies:

razor
@attribute [Authorize(Roles = "Admin")]@attribute [Authorize(Policy = "RequireManager")]

AuthorizeView for conditional UI

razor
<AuthorizeView>    <Authorized>Welcome, @context.User.Identity?.Name!</Authorized>    <NotAuthorized><a href="Account/Login">Log in</a></NotAuthorized></AuthorizeView>

Role/policy variants:

razor
<AuthorizeView Roles="Admin,Manager">    <Authorized>Admin content here</Authorized></AuthorizeView>

Access auth state in code

csharp
[CascadingParameter]private Task<AuthenticationState>? AuthState { get; set; }
protected override async Task OnInitializedAsync(){    if (AuthState is not null)    {        var state = await AuthState;        var isAdmin = state.User.IsInRole("Admin");    }}

Step 5 — Identity pages must stay static SSR

SignInManager and UserManager use HttpContext internally and throw in interactive components. Identity pages (login, register, manage) must render as static SSR.

In a globally interactive app, mark every Identity page:

razor
@page "/Account/Login"@attribute [ExcludeFromInteractiveRouting]

This forces a full-page navigation (exits the interactive circuit) so the page renders through the static SSR pipeline with a real HttpContext.

App.razor must use AcceptsInteractiveRouting() (Step 3) to return null for these pages — otherwise the framework still tries to render them interactively.

In a per-page app, Identity pages are static by default (no @rendermode directive), so [ExcludeFromInteractiveRouting] is not needed.

Step 6 — Auth state in WebAssembly / Auto mode

WebAssembly components run in the browser and have no HttpContext. Auth state must be serialized from the server during prerendering and deserialized on the client.

Server Program.cs:

csharp
builder.Services.AddAuthenticationStateSerialization();

Client .Client/Program.cs:

csharp
builder.Services.AddAuthenticationStateDeserialization();

Without these calls, Task<AuthenticationState> resolves to an anonymous user after WebAssembly takes over from prerendering.

AddAuthenticationStateSerialization accepts options to include role and claim data:

csharp
builder.Services.AddAuthenticationStateSerialization(options =>    options.SerializeAllClaims = true);

Render Mode × Auth Matrix

Render modeHttpContext.UserSignInManagerAuth state sourceKey requirement
Static SSRAvailableWorksServer pipelineUse middleware for redirects, <NotAuthorized> does NOT render
Server (interactive)NOT availableThrowsCascadingAuthenticationStateUse [Authorize] + AuthorizeView, not HttpContext
WebAssemblyNOT availableThrowsSerialized from serverAddAuthenticationStateSerialization / Deserialization
AutoNOT available after WASMThrowsSerialized from serverSame as WebAssembly; register in both Program.cs files

Common Mistakes

MistakeSymptomFix
Using HttpContext.User in interactive componentNull or stale claimsUse [CascadingParameter] Task<AuthenticationState>
SignInManager in interactive componentInvalidOperationExceptionMove to static SSR page with [ExcludeFromInteractiveRouting]
Missing AddAuthenticationStateSerializationAnonymous user after WASM loadsAdd to server Program.cs; add Deserialization to client Program.cs
<NotAuthorized> in static SSR layoutContent never shownStatic SSR uses middleware pipeline; redirect via LoginPath or RedirectToLogin component
Global interactivity without AcceptsInteractiveRoutingIdentity pages crashAdd AcceptsInteractiveRouting() check in App.razor (Step 3)
Missing AddCascadingAuthenticationState()Task<AuthenticationState> is nullRegister in Program.cs (Step 2)

來源與署名

來源:dotnet/skills位於plugins/dotnet-blazor/skills/configure-auth提交0608d89

授權條款: MIT

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架