简体   繁体   English

无法验证防伪令牌

[英]Unable to validate the antiforgery token

I was trying to pass antiforgery token to my HTTPPost method in MVC controller from my js file.我试图从我的 js 文件中将防伪令牌传递给 MVC controller 中的 HTTPPost 方法。 I am getting the following error:我收到以下错误:

"Anti-forgery token validation failed: The required anti-forgery cookie "__RequestVerificationToken" is not present." “防伪令牌验证失败:所需的防伪 cookie“__RequestVerificationToken”不存在。”

When I try to debug the js code and see, I am seeing the token in 'antiForgeryToken' variable.当我尝试调试 js 代码并查看时,我在“antiForgeryToken”变量中看到了令牌。 But not sure what's going on.但不确定发生了什么。 Can someone tell me what wrong am I doing?有人可以告诉我我在做什么错吗? Here is my code from js file:这是我来自 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;  
                                    });
                            }

Here is my action method这是我的操作方法

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

Here is my antiforgery class这是我的防伪 class

[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);
        }
    }

Try to edit this one:尝试编辑这个:

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

To this one:对此:

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

Usually, the AntiForgery token is named __RequestVerificationToken and not an ID with forgeryToken unless you explicitly renamed that.通常,AntiForgery 令牌被命名为__RequestVerificationToken而不是带有forgeryToken的 ID,除非您明确重命名它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM