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

查看:17
本文介绍了如何在表单的 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.

所以,从他们的文档:

为了对非浏览器请求进行简单的保护,Play 只检查请求头中带有 cookie.如果您提出请求AJAX,可以将CSRF token放在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天全站免登陆