Agent Skills › dotnet/skills › configure-auth

configure-auth

GitHub

为 Blazor Web App 配置身份验证与授权,支持不同渲染模式。涵盖服务注册、路由鉴权、页面保护及状态访问,解决交互组件中的认证上下文问题。

plugins/dotnet-blazor/skills/configure-auth/SKILL.md dotnet/skills

Trigger Scenarios

需要添加 [Authorize] 属性或 AuthorizeView 配置登录/注销页面或角色策略访问 处理 Blazor 渲染模式下的认证状态异常

Install

npx skills add dotnet/skills --skill configure-auth -g -y
More Options

Non-standard path

npx skills add https://github.com/dotnet/skills/tree/main/plugins/dotnet-blazor/skills/configure-auth -g -y

Use without installing

npx skills use dotnet/skills@configure-auth

指定 Agent (Claude Code)

npx skills add dotnet/skills --skill configure-auth -a claude-code -g -y

安装 repo 全部 skill

npx skills add dotnet/skills --all -g -y

预览 repo 内 skill

npx skills add dotnet/skills --list

SKILL.md

Frontmatter
{
    "name": "configure-auth",
    "license": "MIT",
    "description": "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)."
}

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

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

For ASP.NET Core Identity add the Identity services:

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.

<!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:

<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

@page "/admin"
@attribute [Authorize]

With roles or policies:

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

AuthorizeView for conditional UI

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

Role/policy variants:

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

Access auth state in code

[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:

@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:

builder.Services.AddAuthenticationStateSerialization();

Client .Client/Program.cs:

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:

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

Render Mode × Auth Matrix

Render mode HttpContext.User SignInManager Auth state source Key requirement
Static SSR Available Works Server pipeline Use middleware for redirects, <NotAuthorized> does NOT render
Server (interactive) NOT available Throws CascadingAuthenticationState Use [Authorize] + AuthorizeView, not HttpContext
WebAssembly NOT available Throws Serialized from server AddAuthenticationStateSerialization / Deserialization
Auto NOT available after WASM Throws Serialized from server Same as WebAssembly; register in both Program.cs files

Common Mistakes

Mistake Symptom Fix
Using HttpContext.User in interactive component Null or stale claims Use [CascadingParameter] Task<AuthenticationState>
SignInManager in interactive component InvalidOperationException Move to static SSR page with [ExcludeFromInteractiveRouting]
Missing AddAuthenticationStateSerialization Anonymous user after WASM loads Add to server Program.cs; add Deserialization to client Program.cs
<NotAuthorized> in static SSR layout Content never shown Static SSR uses middleware pipeline; redirect via LoginPath or RedirectToLogin component
Global interactivity without AcceptsInteractiveRouting Identity pages crash Add AcceptsInteractiveRouting() check in App.razor (Step 3)
Missing AddCascadingAuthenticationState() Task<AuthenticationState> is null Register in Program.cs (Step 2)

Version History

  • 10d85e2 Current 2026-10-19 01:57

    移除技能描述中的 XML 标签以兼容 Claude,并添加校验规则防止回归。

  • ce75c35 2026-07-06 00:29

Same Skill Collection

.agents/skills/create-custom-agent/SKILL.md
.agents/skills/create-skill/SKILL.md
.agents/skills/improve-skill-quality/SKILL.md
.github/skills/agentic-workflows/SKILL.md
eng/skill-validator/tests/fixtures/sample-skill/SKILL.md
plugins/dotnet-advanced/skills/csharp-scripts/SKILL.md
plugins/dotnet-advanced/skills/nuget-trusted-publishing/SKILL.md
plugins/dotnet-advanced/skills/vectorization/SKILL.md
plugins/dotnet-aspnetcore/skills/configuring-opentelemetry-dotnet/SKILL.md
plugins/dotnet-aspnetcore/skills/dotnet-webapi/SKILL.md
plugins/dotnet-aspnetcore/skills/minimal-api-file-upload/SKILL.md
plugins/dotnet-blazor/skills/create-blazor-project/SKILL.md
plugins/dotnet-blazor/skills/fetch-and-send-data/SKILL.md
plugins/dotnet-blazor/skills/support-prerendering/SKILL.md
plugins/dotnet-blazor/skills/use-js-interop/SKILL.md
plugins/dotnet-diag/skills/analyzing-dotnet-performance/SKILL.md
plugins/dotnet-diag/skills/clr-activation-debugging/SKILL.md
plugins/dotnet-diag/skills/dotnet-trace-collect/SKILL.md
plugins/dotnet-diag/skills/dump-collect/SKILL.md
plugins/dotnet-experimental/skills/exp-mock-usage-analysis/SKILL.md
plugins/dotnet-experimental/skills/exp-simd-vectorization/SKILL.md
plugins/dotnet-msbuild/skills/binlog-failure-analysis/SKILL.md
plugins/dotnet-msbuild/skills/build-parallelism/SKILL.md
plugins/dotnet-msbuild/skills/copy-to-output-directory/SKILL.md
plugins/dotnet-msbuild/skills/eliminate-redundant-restores/SKILL.md
plugins/dotnet-msbuild/skills/msbuild-server/SKILL.md
plugins/dotnet-msbuild/skills/resolve-project-references/SKILL.md
plugins/dotnet-test/skills/code-testing-agent/SKILL.md
plugins/dotnet-test/skills/code-testing-extensions/SKILL.md
plugins/dotnet-test/skills/crap-score/SKILL.md
plugins/dotnet-test/skills/filter-syntax/SKILL.md
plugins/dotnet-test/skills/find-untested-sources/SKILL.md
plugins/dotnet-test/skills/test-value-evidence/SKILL.md
plugins/dotnet-upgrade/skills/dotnet-aot-compat/SKILL.md
plugins/dotnet11/skills/process-api-net11/SKILL.md
.agents/skills/authoring-github-workflows/SKILL.md
.agents/skills/create-skill-test/SKILL.md
plugins/dotnet-advanced/skills/dotnet-pinvoke/SKILL.md
plugins/dotnet-ai/skills/mcp-csharp-create/SKILL.md
plugins/dotnet-ai/skills/mcp-csharp-debug/SKILL.md
plugins/dotnet-ai/skills/mcp-csharp-test/SKILL.md
plugins/dotnet-ai/skills/technology-selection/SKILL.md
plugins/dotnet-aspnetcore/skills/convert-blazor-server-to-webapp/SKILL.md
plugins/dotnet-blazor/skills/author-component/SKILL.md
plugins/dotnet-blazor/skills/collect-user-input/SKILL.md
plugins/dotnet-blazor/skills/coordinate-components/SKILL.md
plugins/dotnet-blazor/skills/plan-ui-change/SKILL.md
plugins/dotnet-blazor/skills/use-igniteui-blazor/SKILL.md
plugins/dotnet-data/skills/create-datadriven-aspnetcore/SKILL.md

Metadata

Files
0
Version
10d85e2
Hash
3163cf33
Indexed
2026-07-06 00:29

홈 - 위키
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-10-20 19:35
浙ICP备14020137号-1