在现有的rails webapp上添加protect_from_forgery

时间:2015-01-14 09:17:05

标签: ruby-on-rails csrf

我有一个rails应用程序和一个api一起工作。 该应用程序已有两年时间,并已使用选项(在application_controller中)进行开发:

skip_before_filter :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }
#protect_from_forgery with: :null_session 

因此对CSRF没有任何保护。

我添加了<%= csrf_meta_tag%>在我的所有视图布局上,以及我的application_controller上的protect_from_forgery。

问题是当我的主页面被请求时,会执行一些ajax并且它们不包含CSRF标题,因此我立即注销。

如何在我的应用中引入CSRF保护?

1 个答案:

答案 0 :(得分:0)

您需要更改Ajax请求以包含CSRF令牌。您可以使用以下代码

配置所有AJAX请求以在jQuery中默认发送令牌
$("body").bind("ajaxSend", function(elm, xhr, s){
  if (s.type == "POST") {
    xhr.setRequestHeader('X-CSRF-Token', $('meta[name=csrf-token]').attr('content'));
  }
});

(代码取自this question)。其他JS框架可能具有类似的功能。