问题
I try to create an new person out of an ruby program, for this task i use 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'
I tried to get an authenticity_token by first make an get request to people/new and read out the authenticity_token from the hidden input with nokogiri:
<input name="authenticity_token" type="hidden" value="JKrWBtxcloak2DHucqHtTFZC6W7QyDJoJQI3QtCFBy8=">
Then i make an post request with this authenticity_token, how you can see above.
But somehwo this wont work, my rails console says it has no token authenticity:
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
Do i use an false authenticity token or what do i wrong?
UPDATE::::::::::::::::::::::::::::::::::::::::::::::::::::
I wrote an new programm were i get an set-cookie: But how do i have assign the cookie in my params?
require 'rest_client'
response = RestClient.get("localhost:3000/people/new")
puts response.headers
Output
{: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:
Probably you also have to send
<input name="utf8" type="hidden" value="✓">
来源:https://stackoverflow.com/questions/18693983/rest-client-get-authenticity-token-to-create-new-record