我试图在.Net Core中使用ValidateAntiForgeryToken,但我得到了.AspNetCore.Antiforgery.xxxxxxx cookie丢失了.
这是什么.AspNetCore.Antiforgery.xxxxxxx cookie?
解决方法
ASP.NET Core查找此cookie以查找X-CSRF令牌.
The
ValidateAntiForgeryToken
is an action filter that does Requests made to actions that have this filter applied will be blocked unless the request includes a valid antiforgery token.
通常,ASP.NET Core可能会在cookie或标头中查找令牌.所以你可能会遇到这种情况
>而不是cookie,标头用于传递令牌
>带有令牌的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:
对于以下用途:
services.AddAntiforgery(options => options.Cookie.Name = "X-CSRF-TOKEN-COOKIENAME");
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
调查:
> Preventing Cross-Site Request Forgery (XSRF/CSRF) Attacks in ASP.NET Core
> Antiforgery repo中的自述文件包含样本链接
> SO:Using the antiforgery cookie in ASP.NET Core but with a non-default CookieName