【发布时间】:2018-02-22 19:27:15
【问题描述】:
我试图在 .Net Core 中使用 ValidateAntiForgeryToken 但我得到 .AspNetCore.Antiforgery.xxxxxxx cookie 丢失。
这个 .AspNetCore.Antiforgery.xxxxxxx cookie 是什么?
【问题讨论】:
标签: c# .net asp.net-core .net-core antiforgerytoken
我试图在 .Net Core 中使用 ValidateAntiForgeryToken 但我得到 .AspNetCore.Antiforgery.xxxxxxx cookie 丢失。
这个 .AspNetCore.Antiforgery.xxxxxxx cookie 是什么?
【问题讨论】:
标签: c# .net asp.net-core .net-core antiforgerytoken
ASP.NET Core 查找此 cookie 以找到 X-CSRF 令牌。
ValidateAntiForgeryToken是一个动作过滤器,可应用于单个动作、控制器或应用程序的全局。除非请求包含有效的防伪令牌,否则对应用了此过滤器的操作发出的请求将被阻止。
一般 ASP.NET Core 可能会在 cookie 或标头中查找令牌。所以你可能会遇到这种情况
默认情况下,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:
为此使用以下内容:
services.AddAntiforgery(options => options.Cookie.Name = "X-CSRF-TOKEN-COOKIENAME");
如果谈论标题,名称可以指定:
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
查看:
【讨论】:
Antiforgery,您可以按照此处显示的方式进行配置:github.com/aspnet/Antiforgery/issues/97#issue-169311974