在使用$.ajax发布JSON数据时,如何提供一个AntiForgeryToken?

 2023-02-17    354  

问题描述

我使用了以下帖子的代码:

首先,我将填充一个数组变量,使用正确的控制器操作值.

在使用$.ajax发布JSON数据时,如何提供一个AntiForgeryToken?

使用下面的代码我认为只需将以下行添加到JavaScript代码即可:

即可非常简单

data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();

<%= Html.AntiForgeryToken() %>位于其正确的位置,动作具有[ValidateAntiForgeryToken]

但我的控制器动作一直在说:”无效伪造令牌”

我在这里做错了什么?

代码

data["fiscalyear"] = fiscalyear;
data["subgeography"] = $(list).parent().find('input[name=subGeography]').val();
data["territories"] = new Array();

$(items).each(function() {
    data["territories"].push($(this).find('input[name=territory]').val());
});

    if (url != null) {
        $.ajax(
        {
            dataType: 'JSON',
            contentType: 'application/json; charset=utf-8',
            url: url,
            type: 'POST',
            context: document.body,
            data: JSON.stringify(data),
            success: function() { refresh(); }
        });
    }

推荐答案

自MVC 4.根据此 LINK

  1. 将令牌放在标题中.
  2. 创建一个过滤器.
  3. 将属性放在方法上.

这是我的解决方案:

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

其他推荐答案

是什么是错误的,它应该处理此请求的控制器操作并且用[ValidateAntiForgeryToken]标记为[ValidateAntiForgeryToken]期望称为__RequestVerificationToken的参数与请求一起发布.

在使用JSON.stringify(data)时,没有这样的参数将您的表单转换为其JSON表示,因此抛出异常.

所以我可以看到两个可能的解决方案:

编号1:使用x-www-form-urlencoded而不是JSON发送您的请求参数:

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

2:将请求分为两个参数:

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

所以在所有情况下,您需要发布__RequestVerificationToken值.

其他推荐答案

我只是在我当前的项目中实施这个实际问题.我为所有需要经过身份验证的用户的Ajax帖子做了它.

首先,我决定挂钩我的jquery ajax电话,所以我不经常重复自己.此JavaScript代码段可确保所有Ajax(Post)调用将添加我的请求验证令牌到请求.注意:.NET Framework使用名称__requestVerificationToken,因此我可以使用标准的防CSRF功能,如下所示.

$(document).ready(function () {
    securityToken = $('[name=__RequestVerificationToken]').val();
    $('body').bind('ajaxSend', function (elm, xhr, s) {
        if (s.type == 'POST' && typeof securityToken != 'undefined') {
            if (s.data.length > 0) {
                s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
            else {
                s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
        }
    });
});

在您需要使用令牌的视图中,只需使用常见的HTML助手.您可以在任何地方添加此代码.我将它放在if(request.isauthenticated)声明中:

@Html.AntiForgeryToken() // You can provide a string as salt when needed which needs to match the one on the controller

在控制器中只需使用标准的ASP.NET MVC防CSRF机制.我这样做是这样的(虽然我真的用过盐).

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public JsonResult SomeMethod(string param)
{
    // Do something
    return Json(true);
}

使用Firebug或类似的工具,您可以轻松地看到您的Post请求现在如何附加__requestVerificationToken参数.

以上所述是小编给大家介绍的在使用$.ajax发布JSON数据时,如何提供一个AntiForgeryToken?,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!

原文链接:https://77isp.com/post/34235.html

=========================================

https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。