zoukankan      html  css  js  c++  java
  • How can I supply an AntiForgeryToken when posting JSON data using $.ajax?

    How can I supply an AntiForgeryToken when posting JSON data using $.ajax?

    回答1

    You don't need the ValidationHttpRequestWrapper solution since MVC 4. According to this link.

    1. Put the token in the headers.
    2. Create a filter.
    3. Put the attribute on your method.

    Here is my solution:

    var token = $('input[name="__RequestVerificationToken"]').val();
    var headers = {};
    headers['__RequestVerificationToken'] = token;
    $.ajax({
        type: 'POST',
        url: '/MyTestMethod',
        contentType: 'application/json; charset=utf-8',
        headers: headers,
        data: JSON.stringify({
            Test: 'test'
        }),
        dataType: "json",
        success: function () {},
        error: function (xhr) {}
    });
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
    
            var httpContext = filterContext.HttpContext;
            var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
            AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
        }
    }
    
    
    [HttpPost]
    [AllowAnonymous]
    [ValidateJsonAntiForgeryToken]
    public async Task<JsonResult> MyTestMethod(string Test)
    {
        return Json(true);
    }

    回答2

    What is wrong is that the controller action that is supposed to handle this request and which is marked with the [ValidateAntiForgeryToken] expects a parameter called __RequestVerificationToken to be POSTed along with the request.

    There's no such parameter POSTed as you are using JSON.stringify(data) which converts your form to its JSON representation and so the exception is thrown.

    So I can see two possible solutions here:

    Number 1: Use x-www-form-urlencoded instead of JSON for sending your request parameters:

    data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    data["fiscalyear"] = fiscalyear;
    // ... other data if necessary
    
    $.ajax({
        url: url,
        type: 'POST',
        context: document.body,
        data: data,
        success: function() { refresh(); }
    });

    Number 2: Separate the request into two parameters:

    data["fiscalyear"] = fiscalyear;
    // ... other data if necessary
    var token = $('[name=__RequestVerificationToken]').val();
    
    $.ajax({
        url: url,
        type: 'POST',
        context: document.body,
        data: { __RequestVerificationToken: token, jsonRequest: JSON.stringify(data) },
        success: function() { refresh(); }
    });

    So in all cases you need to POST the __RequestVerificationToken value.

  • 相关阅读:
    自然语言处理NLP快速入门
    2019年机器学习:追踪人工智能发展之路
    中科院院士谭铁牛:人工智能发展需要理性务实
    SAP MM ME21N 创建PO时报错
    最全的机器学习资料
    SAP MM盘点流程里如何处理事务代码MI11 Recount过的盘点凭证?
    如何“快”、“准”、“狠”成为优秀算法工程师
    解码以色列人工智能产业:正在崛起的竞争者
    周志华:关于机器学习的一点思考
    projects
  • 原文地址:https://www.cnblogs.com/chucklu/p/13713952.html
Copyright © 2011-2022 走看看