Rails post can't verify CSRF token authenticity

假如想象 提交于 2019-12-24 00:35:26

问题


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.

Here is my ajax

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

If I add this

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.


回答1:


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

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);
    }
});

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.



来源:https://stackoverflow.com/questions/37337691/rails-post-cant-verify-csrf-token-authenticity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!