反伪造令牌验证失败。提供的防伪令牌验证失败。 Cookie令牌和请求令牌已交换

时间:2019-11-05 18:59:24

标签: c# asp.net-mvc-5 csrf asp.net-core-2.2 x-xsrf-token

我在AutoValidateAntiforgeryTokenAttribute处遇到错误

错误: 反伪造令牌验证失败。提供的防伪令牌验证失败。 cookie令牌和请求令牌已交换。 过滤器“ Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.AutoValidateAntiforgeryTokenAuthorizationFilter”处的请求授权失败。

我已经在线搜索了,而StackOverflow却无济于事。请让我知道我在这里犯什么错误。

在startup.cs

       services.AddMvc(options =>
       {
            options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
       }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

       services.AddCors(options =>
       {
           options.AddPolicy("AllowAllOrigins",
               builder => { builder.AllowAnyOrigin(); });
       });

       services.AddAntiforgery(options =>
       {
           options.HeaderName = "X-XSRF-TOKEN";
           options.SuppressXFrameOptionsHeader = false;
       });

我将cookie设置如下

 var tokens = _antiforgery.GetAndStoreTokens(_httpContextAccessor.HttpContext);

 Response.Cookies.Append("XSRF-TOKEN", tokens.CookieToken,
                new CookieOptions { HttpOnly = false });
            Response.Cookies.Append("X-CSRF-FORM-TOKEN", tokens.RequestToken,
                new CookieOptions { HttpOnly = false });

从开发人员窗口中,我可以看到值已正确设置

enter image description here

在请求标头中传递了相同的值

enter image description here

0 个答案:

没有答案