【问题标题】:how to Set Request Header "XSRF-TOKEN" to Dynamically create <input>s in a form and submit it如何设置请求标头“XSRF-TOKEN”以在表单中动态创建 <input> 并提交
【发布时间】:2021-01-28 14:40:28
【问题描述】:

请考虑以下代码 sn-p :

function dynamicallyPostForm(path, params, method = 'post') {
    const form = document.createElement('form');
    form.method = method;
    form.action = path;
    for (const key in params) {
        if (params.hasOwnProperty(key)) {
            const hiddenField = document.createElement('input');
            hiddenField.type = 'hidden';
            hiddenField.name = key;
            hiddenField.value = params[key];
            form.appendChild(hiddenField);
        }
    }
    document.body.appendChild(form);
    form.submit();
}

dynamicallyPostForm('/contact/', {name: 'Johnny Bravo'});

如何设置Request Header XSRF-TOKEN? : (提示:我的项目在 asp.net mvc 核心中并在控制器中使用了 [ValidateAntiForgeryToken])

【问题讨论】:

  • 也许this 有帮助?答案还简要说明了如何使用 jQuery 设置这个 xsrf-token 标头属性。

标签: javascript jquery asp.net-core-mvc


【解决方案1】:

简短的回答是否定的。提交表单时没有浏览器端设置任意 HTTP 请求标头的工具。

此外,如果您在 asp.net core 中没有任何特殊设置。 ValidateAntiForgeryToken 将检查表单数据的__RequestVerificationToken 而不是标题XSRF-TOKEN

这就是 validate AntiForgery 的工作原理:

1.客户端请求一个包含表单的 HTML 页面。

2.服务器在响应中包含两个令牌。一个令牌作为 cookie 发送。另一个放置在隐藏的表单域中。令牌是随机生成的,因此对手无法猜测值。

3.当客户端提交表单时,它必须将两个令牌都发送回服务器。客户端将 cookie 令牌作为 cookie 发送,并在表单数据中发送表单令牌。 (当用户提交表单时,浏览器客户端会自动执行此操作。)

4.如果请求不包含两个令牌,则服务器不允许该请求。

所以最简单的方法是将令牌设置为隐藏字段并回发,如下所示:

@Html.AntiForgeryToken()

<input type="button" onclick="dynamicallyPostForm('TestWithAnti', {name: 'Johnny Bravo'});" />

@section scripts{

    <script>


        function dynamicallyPostForm(path, params, method = 'post') {
            const form = document.createElement('form');
            form.method = method;
            form.action = path;
            for (const key in params) {
                if (params.hasOwnProperty(key)) {
                    const hiddenField = document.createElement('input');
                    hiddenField.type = 'hidden';
                    hiddenField.name = key;
                    hiddenField.value = params[key];
                    form.appendChild(hiddenField);
                }
            }
            //get the token and append into new form
            const hiddenField = document.createElement('input');
            hiddenField.type = 'hidden';
            hiddenField.name = '__RequestVerificationToken';
            hiddenField.value = document.getElementsByName('__RequestVerificationToken')[0].value;
            form.appendChild(hiddenField);

            document.body.appendChild(form);
            form.submit();
        }
    </script>

}

结果:

【讨论】:

    猜你喜欢
    • 2021-02-17
    • 2021-07-07
    • 2018-09-06
    • 2020-03-30
    • 2011-12-21
    • 1970-01-01
    • 2023-03-30
    • 2016-12-16
    • 1970-01-01
    相关资源
    最近更新 更多