我尝试从 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 请求并使用 nokogiri 从隐藏输入中读取authentity_token 来获取authentity_token:
<input name="authenticity_token" type="hidden" value="JKrWBtxcloak2DHucqHtTFZC6W7QyDJoJQI3QtCFBy8=">
然后我用这个authenticity_token发出一个post请求,你可以在上面看到。
但是这不起作用,我的 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
我是否使用了虚假的真实性令牌或我做错了什么?
更新::::::::::::::::::::::::::::::::::::::::::::::::: :::
我写了一个新程序,如果我得到一个 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"]}