You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET8 Blazor Server中AntiforgeryToken未生成__RequestVerificationToken字段问题

问题分析与解决方案

核心错误点

  1. 缺失关键中间件且顺序错误
    你在Program.cs中注释掉了app.UseAuthentication()和app.UseAuthorization(),这两个是Identity认证功能的必需中间件。同时,中间件执行顺序不符合要求:UseAntiforgery()必须放在UseAuthentication()和UseAuthorization()之后,才能基于认证上下文生成有效的防伪造令牌。

  2. 防伪造令牌未正确生成
    由于认证中间件缺失,AntiforgeryToken组件无法获取有效的防伪造令牌上下文,因此无法渲染出__RequestVerificationToken隐藏字段,导致表单提交时令牌验证失败。

修复步骤

1. 修正Program.cs的中间件配置

恢复认证授权中间件,并调整至正确顺序:

var app = builder.Build();

if (app.Environment.IsDevelopment())
    app.UseMigrationsEndPoint();
else
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

// 恢复认证与授权中间件,必须放在UseAntiforgery之前
app.UseAuthentication();
app.UseAuthorization();

app.UseAntiforgery();

app.MapRazorComponents<App>().AddInteractiveServerRenderMode();
app.MapAdditionalIdentityEndpoints();

app.Run();

2. 确保防伪造令牌正确渲染

如果AntiforgeryToken组件仍无法正常工作,可通过注入IAntiforgery服务手动生成令牌字段:
修改Toolbar组件代码:

@inject IAntiforgery Antiforgery
@inject NavigationManager NavManager

<AuthorizeView>
    <Authorized>
        @{
            var tokenSet = Antiforgery.GetAndStoreTokens(NavManager);
        }
        <form action="Account/Logout" method="post">
            <input type="hidden" name="__RequestVerificationToken" value="@tokenSet.RequestToken" />
            <input type="hidden" name="ReturnUrl" value="@NavManager.Uri" />
            <button type="submit">Sign out</button>
        </form>
    </Authorized>
</AuthorizeView>

3. 验证App.razor的基础配置

确保App.razor保留模板中的认证级联和路由结构,这是Identity功能正常运行的基础:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(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>
        <NotFound>
            <PageTitle>Not found</PageTitle>
            <LayoutView Layout="@typeof(MainLayout)">
                <p role="alert">Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

说明

MapAdditionalIdentityEndpoints()会自动注册包括/Account/Logout在内的Identity端点,因此表单的action路径是正确的。修复中间件配置后,防伪造令牌就能正常生成并通过验证,注销功能即可正常工作。

内容的提问来源于stack exchange,提问作者Alisbha Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 16:34:56