c# - .Net Core 中的 .AspNetCore.Antiforgery.xxxxxxx cookie 是什么?

标签 c# .net asp.net-core .net-core antiforgerytoken

我试图在 .Net Core 中使用 ValidateAntiForgeryToken,但我得到的是 .AspNetCore.Antiforgery.xxxxxxx cookie 丢失。

这个 .AspNetCore.Antiforgery.xxxxxxx cookie 是什么?

最佳答案

ASP.NET Core 查找此 cookie 以找到 X-CSRF token 。

The ValidateAntiForgeryToken is an action filter that can be applied to an individual action, a controller, or globally for the app. Requests made to actions that have this filter applied will be blocked unless the request includes a valid antiforgery token.

一般而言,ASP.NET Core 可能会在 cookie 或 header 中查找 token 。所以你可能会遇到这样的情况

  • 使用 header 代替 cookie 来传递 token
  • 带有 token 的 cookie 的名称与 ASP.NET Core 预期的名称不同。

默认情况下,ASP.NET Core 将生成并期望一个以 DefaultCookiePrefix (".AspNetCore.Antiforgery.") 开头的唯一 cookie 名称。

这可以使用防伪选项 CookieName 覆盖:

services.AddAntiforgery(options => options.CookieName = "X-CSRF-TOKEN-COOKIENAME");

对于 .Net Core 2.0.0 or greater there will be changes :

引用: https://learn.microsoft.com/en-us/dotnet/api/Microsoft.AspNetCore.Antiforgery.AntiforgeryOptions?view=aspnetcore-2.0

为此使用以下内容:

services.AddAntiforgery(options => options.Cookie.Name = "X-CSRF-TOKEN-COOKIENAME");

如果谈论标题,名称可以指定为:

services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

调查:

关于c# - .Net Core 中的 .AspNetCore.Antiforgery.xxxxxxx cookie 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46208476/

相关文章:

c# - .net 中的数据同步设计

c# - FindLast 在 IEnumerable 上

c# - 如何将 Linq 扩展方法重写为委托(delegate)?

.net - AppDomain.CreateInstance 不遵守规则

asp.net - asp.net-vnext 中的旧程序集引用错误

json - 如何使用 ConfigurationBuilder 解析现有的 json 字符串(不是文件)

c# - 在 C# 中,您可以使 Windows 窗体应用程序作为服务启动吗?

c# - PrimaryScreen.Size 的问题

c# - await Task.Run(ioBoundOperation) 是否等于 ioBoundOperation?

c# - .NET 软件更新管理器