Rest-Client获取authenticity_token以创建新记录

时间:2013-09-09 08:09:50

标签: ruby-on-rails ruby ruby-on-rails-3 authentication

我尝试用ruby程序创建一个新人,为此任务我使用rest-client:

require 'rest_client'
require 'nokogiri'

page = Nokogiri::HTML(RestClient.get("localhost:3000/people/new"))  

token = page.css("input[name='authenticity_token']")
token2 = token[0]["value"]

RestClient.post 'localhost:3000/people', :authenticity_token => token2, :person => {:name => 'Joseph'}, :commit => 'Create Person'

我试图通过首先向people / new发出get请求来获取authenticity_token,并使用nokogiri从隐藏的输入中读出authenticity_token:

<input name="authenticity_token" type="hidden" value="JKrWBtxcloak2DHucqHtTFZC6W7QyDJoJQI3QtCFBy8=">

然后我用这个authenticity_token发帖请求,你怎么看上面。

但有些情况不会奏效,我的rails控制台表示它没有令牌真实性:

 Started POST "/people" for 127.0.0.1 at 2013-09-09 09:33:27 +0200
 Processing by PeopleController#create as XML
 Parameters: {"authenticity_token"=>"WnbZY/060H5IMGdpVMyRKwG/CHKNAEGafOV3i1f8Kj
 o=", "person"=>{"name"=>"Joseph"}, "commit"=>"Create Person"}
 WARNING: Can't verify CSRF token authenticity

我是否使用虚假的真实性令牌或我错了什么?

UPDATE :::::::::::::::::::::::::::::::::::::::::::::: ::::::

我写了一个新的程序,我得到了一个set-cookie:但是我如何在我的参数中分配cookie?

 require 'rest_client'

 response = RestClient.get("localhost:3000/people/new")
 puts response.headers

输出

 {:content_type=>"text/html; charset=utf-8", :x_ua_compatible=>"IE=Edge", :etag=>
 "\"aeb1c39272f16046456cf66c53a9ee7c\"", :cache_control=>"max-age=0, private, mus
 t-revalidate", :x_request_id=>"87d76be013cb156113b15c11875edeaa", :x_runtime=>"0
 .025002", :server=>"WEBrick/1.3.1 (Ruby/1.9.3/2013-02-22)", :date=>"Mon, 09 Sep
 2013 09:08:36 GMT", :content_length=>"1407", :connection=>"Keep-Alive", :set_coo
 kie=>["_rumba_session=BAh7B0kiD3Nlc3Npb25faWQGOgZFRkkiJTBjMWI3YTkzZjI0MjZmZmE4Zm
 QwMzI4ZGE1NmRhNWU3BjsAVEkiEF9jc3JmX3Rva2VuBjsARkkiMWxqemZjUUMyNG81T2diZjFRN2ZNZn
 ljMFNmalp4NUtLcXZhcnVocWcxQWc9BjsARg%3D%3D--3439371de3cba7c2352eace74051858dcc13
 7333; path=/; HttpOnly"]}

1 个答案:

答案 0 :(得分:0)

可能你也必须发送

<input name="utf8" type="hidden" value="✓">