Rails 3.1-CSRF被忽略了吗? [英] Rails 3.1 - CSRF ignored?

查看:70
本文介绍了Rails 3.1-CSRF被忽略了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题,

我有一个Rails 3.1应用程序,我正在尝试发出ajax请求,但收到警告消息警告:无法验证CSRF令牌的真实性"…

I've got a rails 3.1 app and I'm trying to make an ajax request but I get the warning message "WARNING: Can't verify CSRF token authenticity"…

在我的布局中,我有帮助方法"csrf_method_tag" ,并且添加了以下javascript代码(不知道它是否确实需要):

Inside my layout I've got the helper method "csrf_method_tag", and I add the following javascript code (don't know if it's really required or not):

$.ajaxSetup({
  beforeSend: function(xhr) {
    xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
  }
});

我的Gemfile包含宝石 jquery-rails (> = 1.0.12),我需要jquery& jquery-ujs位于我的application.js顶部.

My Gemfile contains the gem jquery-rails (>= 1.0.12) and I require jquery & jquery-ujs at the top of my application.js.

即使如此,该消息仍然会出现.我忘了什么吗?

Even with that, the message still appears. Did i forget something?

感谢您的帮助.

推荐答案

对我有用的-当不使用表单时-将<%= form_authenticity_token %>的结果包括在ajax数据有效载荷中.因此,我做的事情类似于tehprofessor在html中建议的内容:

What's worked for me - when working without forms - is to include the result of <%= form_authenticity_token %> in the ajax data payload. So I do something like what was suggested by tehprofessor in the html:

<input id="tokentag" type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>" />

然后使用javascript:

then in the javascript:

tokentag = $('#tokentag').val()
submitdata = { "authenticity_token": tokentag, ...+whatever else you need to include+...}

然后用submitdata调用$.ajax.

这篇关于Rails 3.1-CSRF被忽略了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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