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

What is .AspNetCore.Antiforgery.xxxxxxx cookie in .Net Core?

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

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

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

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 中寻找令牌。所以你可能会遇到

的情况
  • 而不是 cookie header 用于传递令牌
  • 带有令牌的 cookie 的名称与预期的 ASP.NET 核心不同。

默认情况下,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://docs.microsoft.com/en-us/dotnet/api/Microsoft.AspNetCore.Antiforgery.AntiforgeryOptions?view=aspnetcore-2.0

为此使用以下内容:

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

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

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

调查: