获取json post请求到rails应用程序的csrf令牌

获取json post请求到rails应用程序的csrf令牌,json,ruby-on-rails-3.1,csrf,rest-client,Json,Ruby On Rails 3.1,Csrf,Rest Client,我一直在使用rest客户端访问我编写的rails应用程序。我已经编写了一个快速脚本来登录并发出post请求。一切都正常,但我必须解决一个事实,即如果您请求使用json格式的表单,则不会提供任何令牌。我必须以其他方式发出一个常规html请求以获取Authentity_令牌,然后将其包含在作为post请求一部分提交的json中。基本上我有一个快速的脏脚本,如下面的一个 private_resource = RestClient::Resource.new( 'https://mysite.com')

我一直在使用rest客户端访问我编写的rails应用程序。我已经编写了一个快速脚本来登录并发出post请求。一切都正常,但我必须解决一个事实,即如果您请求使用json格式的表单,则不会提供任何令牌。我必须以其他方式发出一个常规html请求以获取Authentity_令牌,然后将其包含在作为post请求一部分提交的json中。基本上我有一个快速的脏脚本,如下面的一个

private_resource = RestClient::Resource.new( 'https://mysite.com')

params =  {:user => {:email => 'user@mysite.com', :password => 'please'}}
#log in
login_response = private_resource['users/sign_in'].post(params, :content_type => :json, :accept => :json)
#get cookie
cookie = login_response.cookies
#get json  
json_response = private_resource['products/new'].get(:content_type => :json, :accept => :json, :cookies => cookie)
#another request that returns html form with authenticity token 
response_with_token = private_resource['products/new'].get( :cookies => cookie)
#extract token 
token = Nokogiri::XML(response_with_token).css('input[name=authenticity_token]').first.attr('value')
#update cookie
cookie = response_with_token.cookies
#populate form and insert token
form = JSON.parse(json_response)
form['name'] = "my product"
form['authenticity_token'] = token
#submit the request
private_resource['products'].post(form.to_json, {:cookies => cookie, :content_type => :json, :accept => :json})
可以选择关闭json请求的CSRF保护,但我不希望这样做。我可以走机械化路线或类似的路线,这样我就不用担心CSRF的json请求了,但我只想在rest客户机上做这件事


我想我只是想知道为什么没有为json请求提供Authentity_令牌是有原因的,我还想知道是否有比我在这里采用的非常粗糙的方法更好的解决令牌问题的方法

将以下代码放入您的应用程序控制器中:

def verified_request?
    if request.content_type == "application/json"
      true
    else
      super()
    end
end
并使用before_filter调用此方法

有关更多详细信息,请查看:


并在rails中检查此问题:

在您的
应用程序/views/products/new.json.jbuilder
中,添加以下内容:

json.authenticity_token form_authenticity_token

这将插入一个键
“authenticity\u token”
,其值为token,因此在
json\u响应中也会得到token。来自的想法。

谢谢您的回复,swati,它看起来很有用。我想虽然我只是想避免关闭CSRF检查。我觉得有点奇怪,rails提供的json表单不包含任何令牌,但会检查令牌。只提供包含令牌的json表单,而不是关闭json内容的检查,这有意义吗?欢迎。。。是的,这是绕过CSRF代币问题的唯一方法。如果希望在JSON请求中传递令牌,可以使用如下标题:{'X-CSRF-token':''}检查: