私が書いたレールアプリにアクセスするためにrest-clientを使って遊んでいます。ログインして投稿リクエストを行う簡単なスクリプトを作成しました。すべてが機能していますが、json でフォームをリクエストした場合、authenticity_token が提供されないという事実に対処する必要がありました。私は通常のhtmlリクエストを作成してauthenticity_tokenを取得し、これを投稿リクエストの一部として送信した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-clientでこのことを試してみたかっただけです
私は、authenticity_token が json リクエストに対して提供されない理由があるかどうかを知りたいだけだと思います。また、ここで取ったかなりハックなアプローチよりもトークンの問題を解決するより良い方法があるかどうかも疑問に思っています。