【问题标题】:Unable to validate the antiforgery token无法验证防伪令牌
【发布时间】:2021-06-09 21:34:03
【问题描述】:

我试图从我的 js 文件将防伪令牌传递给 MVC 控制器中的 HTTPPost 方法。我收到以下错误:

“防伪令牌验证失败:所需的防伪cookie“__RequestVerificationToken”不存在。”

当我尝试调试 js 代码并查看时,我在“antiForgeryToken”变量中看到了令牌。但不确定发生了什么。有人可以告诉我我在做什么错吗?这是我的 js 文件中的代码:

options.data = function (find) {
                                var antiForgeryToken = $("#forgeryToken").val();
                                fetch('/Options/Students/StudentScore',
                                    {
                                        method: 'POST',
                                        body: JSON.stringify({
                                            find: find,
                                            querystringParams: querystringParams
                                        }),
                                        headers: {
                                            "Content-type": "application/json; charset=UTF-8",
                                            "RequestVerificationToken": antiForgeryToken
                                        } 
                                    })
                                    .then(function (response) { return response.json() })
                                    .then(function (response) {
                                        var mapped = _.map(response.Results,
                                            function(i) {
                                                return {
                                                    DisplayValue: i.text
                                                }
                                            });
                                        return mapped;
                                    })
                                    .catch(function(err) {
                                        debugger;  
                                    });
                            }

这是我的操作方法

        [System.Web.Mvc.HttpPost]
        [ValidateAntiForgeryTokenAttribute]
        public async Task<ActionResult> StudentScore([FromBody] StudentValues request)
        {
            //Implementation
            return JsonNet(sometestval, JsonRequestBehavior.AllowGet);
        }

这是我的防伪课

[AttributeUsage(AttributeTargets.Method)]
    public class ValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            try
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    ValidateRequestHeader(filterContext.HttpContext.Request);
                }
                else
                {
                    AntiForgery.Validate();
                }
                    
            }
            catch(Exception e)
            {
                throws exception;
            }
        }

        private static void ValidateRequestHeader(HttpRequestBase request)
        {
            var cookieToken = string.Empty;
            var formToken = string.Empty;
            var tokenValue = request.Headers["RequestVerificationToken"];
            if (!string.IsNullOrEmpty(tokenValue))
            {
                var tokens = tokenValue.Split(':');
                if (tokens.Length == 2)
                {
                    cookieToken = tokens[0].Trim();
                    formToken = tokens[1].Trim();
                }
            }

            AntiForgery.Validate(cookieToken, formToken);
        }
    }

【问题讨论】:

  • 正如Willy David Jr所说,你需要从$('input[name="__RequestVerificationToken"]')获取数据。如果你没有输入名字是__RequestVerificationToken,你需要将@Html.AntiForgeryToken()&lt;form method="post"&gt;&lt;/form&gt; 添加到您的视图中。

标签: c# asp.net-mvc asp.net-core razor antiforgerytoken


【解决方案1】:

尝试编辑这个:

var antiForgeryToken = $("#forgeryToken").val();

到这个:

var antiForgeryToken = $('input[name="__RequestVerificationToken"]').val();

通常,AntiForgery 令牌被命名为 __RequestVerificationToken,而不是带有 forgeryToken 的 ID,除非您明确重命名。

【讨论】:

    猜你喜欢
    • 2020-04-27
    • 2014-01-23
    • 1970-01-01
    • 2017-07-21
    • 2023-03-30
    • 2018-06-19
    • 2016-05-07
    • 1970-01-01
    相关资源
    最近更新 更多