jquery - Ajax POST 中不存在 __RequestVerificationToken

标签 jquery asp.net-mvc csrf-protection antiforgerytoken

我正在使用 jQuery DataTales 从 MVC5 请求 POST URL 并尝试添加防伪 token 。我已将其添加到 header 和请求正文中,但仍然收到 500 错误:“所需的防伪表单字段“__RequestVerificationToken”不存在。”

形式:

<form id="my-units-form" action="@Url.Action("MyUnitsResults", "Provider")" class="form-horizontal criteria well well-sm">
    @Html.AntiForgeryToken()
    ....

JavaScript:

$userDt = $('#users-table')
    .DataTable({
        serverSide: true,
        ordering: false,
        searching: true,
        ajax: {
            "url": url,
            "type": "POST",
            'contentType': 'application/json',
            "dataType": "json",
            headers: { '__RequestVerificationToken': $('form input[name=__RequestVerificationToken]').val() },
            data: function (d) {
                d.__RequestVerificationToken= $('form input[name=__RequestVerificationToken]').val();

                return JSON.stringify(d);
            }
        },

Headers

Payload

最佳答案

如果您对数据进行字符串化并使用 contentType: 'application/json,则仅将 token 添加到 ajax header (不会从正文中读取)。

然后,您需要创建一个自定义 FilterAttribute 来从标题中读取值

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class ValidateHeaderAntiForgeryTokenAttribute : 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"]);
    }
}

并在您的 Controller 方法中,将 [ValidateAntiForgeryToken] 属性替换为 [ValidateHeaderAntiForgeryToken]

关于jquery - Ajax POST 中不存在 __RequestVerificationToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46468376/

相关文章:

javascript - 如何在等待渲染 Reactjs 时进行加载

jquery - 如何使用jquery获取选定选项的数量?

jquery - 第 2 部分。选择和更改具有特定背景颜色的元素

jquery - 数据表分页最初不起作用

c# - 将 View 渲染为字符串缓存问题

asp.net-mvc - ASP.NET MVC – Controller 测试的模拟成员

css - 同一行的标签和文本框+整个宽度的文本框

javascript - 为 window.location.href 添加 CSRF token

caching - 避免CSRF token

node.js - 在 React/Redux 应用程序的 cookie 中保护 JWT 的最佳方法是什么?