Rails帖子无法验证CSRF令牌的真实性 [英] Rails post can't verify CSRF token authenticity

查看:111
本文介绍了Rails帖子无法验证CSRF令牌的真实性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经查看了这个警告:无法验证CSRF令牌的真实性
但我仍然无法弄明白为什么会导致此错误。

I've check this WARNING: Can't verify CSRF token authenticity rails but I still can't figure it out why it cause this error.

这是我的 ajax

 $.post(
      "<%= ajax_chats_path %>",
      {timestamp :(new Date()).getTime(),msg: $('#msg').val()},
      function (json) {
      console.log(json);
    });

如果我添加

skip_before_action :verify_authenticity_token

在控制器中,它可以解决这个问题。

in controller, it can solve this problem.

我不确定这是正确的做法,因为它看起来可能会遇到一些安全攻击。

I am not sure it's the right way to do, because it looks like it may encounter some security attack.

推荐答案

您在Ajax调用中缺少CSRF令牌。您需要使用长格式$ .ajax调用,并添加以下内容:

You're missing the CSRF token in your Ajax call. You'll need to use a long-form $.ajax call, and add this:

beforeSend: $.rails.CSRFProtection

而不是 $。发布,你可以使用 $。ajax 等价物,如下所示:

Instead of $.post, you can use the $.ajax equivalent, which would look like this:

$.ajax({
    type: "POST",
    url: "<%= ajax_chats_path %>",
    beforeSend: $.rails.CSRFProtection,
    data: {
        timestamp: (new Date()).getTime(),
        msg: $('#msg').val(),
        beforeSend: $.rails.CSRFProtection
    },
    success: function (json) {
      console.log(json);
    }
});

您还应该强烈考虑添加数据类型调用字段,以便jQuery知道响应的处理并相应地处理它。您可以选择xml,json,html,script,jsonp或text中的任何一个。有关详细信息,请参阅 jQuery.ajax()API文档

You should also strongly consider adding the datatype field to the call, so that jQuery knows the disposition of the response and can handle it accordingly. You can choose from any of "xml", "json", "html", "script", "jsonp", or "text". See the jQuery.ajax() API documentation for more details.

这篇关于Rails帖子无法验证CSRF令牌的真实性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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