如何在表单的AJAX发布请求中传递CSRF令牌? [英] How to pass along CSRF token in an AJAX post request for a form?

查看:118
本文介绍了如何在表单的AJAX发布请求中传递CSRF令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Scala Play! 2.6框架,但这可能不是问题.我正在使用他们的Javascript路由-似乎可以正常工作,但出现了问题.我有一个带有CSRF令牌的表单,在渲染时会产生这种情况:

I'm using Scala Play! 2.6 Framework, but that may not be the issue. I'm using their Javascript routing - and it seems to work ok, but it's having issues. I have a form, which when rendered produces this, with a CSRF token:

<form method="post" id="myForm" action="someURL">

<input name="csrfToken" value="5965f0d244b7d32b334eff840...etc" type="hidden">
  <input type="text" id="sometext">
  <button type="submit"> Submit! </button>

</form>

这大概是我的AJAX:

And here's roughly, my AJAX:

$(document).on('submit', '#myForm', function (event) {

 event.preventDefault();
   var data = {
    textvalue: $('#sometext').val()
   }
 var route = jsRoutes.controllers.DashboardController.postNewProject()
 $.ajax({
    url: route.url,
    type: route.type,
    data : JSON.stringify(data),
    contentType : 'application/json',
    success: function (data) { ...      },
    error: function (data) { ...  }
        })

});

但是,当我发布此消息时,我的服务器返回了未经授权的响应,并且IntelliJ中的控制台告诉我CSRF检查失败.如何在请求中传递CSRF令牌?

But when I post this, I am getting an UNAUTHORIZED response back from my Server, and my console in IntelliJ is telling me the CSRF check is failing. How would I pass along the CSRF token in the request?

推荐答案

好吧,经过了几个小时的尝试,并尝试在

Ok, after fighting this for a few hours and trying to decrypt Play's frequently-lacking-context-Documentation on the subject, I've got it.

因此,根据他们的文档:

So, from their docs:

要为非浏览器请求提供简单保护,请仅播放检查 标头中包含Cookie的请求.如果您正在与 AJAX,您可以将CSRF令牌放在HTML页面中,然后添加它 使用Csrf-Token标头访问请求.

To allow simple protection for non browser requests, Play only checks requests with cookies in the header. If you are making requests with AJAX, you can place the CSRF token in the HTML page, and then add it to the request using the Csrf-Token header.

然后没有代码或示例.谢谢玩.非常具有描述性.无论如何,这是怎么做的:

And then there's no code or example. Thanks Play. Very descriptive. Anyway, here's how:

在您的view.html.formTemplate中,您可以用IntelliJ编写:

in your view.html.formTemplate you might write in IntelliJ:

@()
<form method="post" id="myForm" action="someURL">

@helper.CSRF.formField  <!-- This auto-generates a token for you -->
  <input type="text" id="sometext">
  <button type="submit"> Submit! </button>

</form>

当交付给客户端时,它将呈现如下形式:

And this will render like this when delivered to the client:

<form method="post" id="myForm" action="someURL">

<input name="csrfToken" value="5965f0d244b7d32b334eff840...etc" type="hidden">
  <input type="text" id="sometext">
  <button type="submit"> Submit! </button>

</form>

好吧,几乎到了,现在我们必须创建AJAX调用.我的所有文件都放在一个单独的main.js文件中,但是如果需要,您也可以将其放在view.html.formTemplate中.

Ok, almost there, now we have to create our AJAX call. I have all of mine in a separate main.js file, but you could also put this in your view.html.formTemplate if you want.

$(document).on('submit', '#myForm', function (event) {

 event.preventDefault();
   var data = {
    myTextToPass: $('#sometext').val()
   }
 // LOOK AT ME! BETWEEN HERE AND
 var token =  $('input[name="csrfToken"]').attr('value')
    $.ajaxSetup({
        beforeSend: function(xhr) {
            xhr.setRequestHeader('Csrf-Token', token);
        }
    });
// HERE
 var route = jsRoutes.controllers.DashboardController.postNewProject()
 $.ajax({
    url: route.url,
    type: route.type,
    data : JSON.stringify(data),
    contentType : 'application/json',
    success: function (data) { ...      },
    error: function (data) { ...  }
        })

});

在此行中: var token = $('input[name="csrfToken"]').attr('value') 您将提取在表单字段中自动生成的CSRF令牌,并在要在Javascript中使用的var中获取其值.

With this line: var token = $('input[name="csrfToken"]').attr('value') You are plucking out the CSRF token auto generated in your form field and grabbing its value in a var to be used in your Javascript.

所有AJAX的另一个重要组成部分在这里:

The other important chunk from all that AJAX is here:

$.ajaxSetup({
            beforeSend: function(xhr) {
                xhr.setRequestHeader('Csrf-Token', token);
            }
        });

使用$.ajaxSetup,您可以设置标题中的内容.这是您从他们的文档中得出的结论:

Using the $.ajaxSetup, you can set what's in the header. This is what you have to infer from their documentation:

使用Csrf-Token标头将其添加到请求中.

add it to the request using the Csrf-Token header.

祝你好运!让我知道是否清楚.

Good luck! Let me know if this is clear.

注意:使用 lusca 时,请使用X-CSRF-Token代替Csrf-Token.

Note: when using lusca, use X-CSRF-Token instead of Csrf-Token.

这篇关于如何在表单的AJAX发布请求中传递CSRF令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆