AntiforgeryToken 未生成 __RequestVerificationToken 隐藏字段 Blazor 服务器

问题描述 投票:0回答:1

我有一个使用 .NET8 Blazor 和 InteractiveServerRenderMode 构建的应用程序。

App.razor 的配置与您创建具有全局交互性和身份的 Blazor 服务器应用程序时获得的模板类似。

我有一个工具栏组件,我正在尝试使用以下形式添加SignOut功能

<AuthorizeView>
<Authorized>
<form action="Account/Logout" method="post">
    <AntiforgeryToken />
    <input type="hidden" name="ReturnUrl" value="@currentUrl" />
   <button type="submit">Sign out</button>
</form>
</Authorized>
</AuthorizeView>

但是当我使用“注销”按钮提交此表单时,出现以下错误

BadHttpRequestException:读取时发现无效的防伪令牌 请求正文中的参数“string returnUrl”作为表单。

此错误是正确的,因为当我检查元素时,我没有看到 __RequestVerificationToken 字段。它没有被渲染,我什至尝试使用

@attribute [RequireAntiforgeryToken]
但它仍然不起作用。

我还尝试在 Program.cs 中将其注册为

builder.Services.AddAntiforgery();

谁能指出我在这里做错了什么?

asp.net-core blazor antiforgerytoken
1个回答
0
投票

BadHttpRequestException:从请求正文中以表单形式读取参数“string returnUrl”时发现无效的防伪令牌。

根据错误信息,您应该确保已将

app.UseAntiforgery();
中间件放入program.cs中。

更多详情,可以参考以下代码:

...
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();
app.UseAntiforgery();

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

// Add additional endpoints required by the Identity /Account Razor components.
app.MapAdditionalIdentityEndpoints();

app.Run();

结果:

© www.soinside.com 2019 - 2024. All rights reserved.