2012-05-02 27 views
8

私は書いたレールアプリにrest-clientを使って遊んでいました。私はログインして投稿要求をするための簡単なスクリプトを書いています。すべてが動作していますが、jsonでフォームをリクエストすると、authenticity_tokenは提供されないという事実を処理しなければなりませんでした。私はauthenticity_tokenを取得してから、通常のhtmlリクエストを作成しなければなりませんでした。そして、これを私の投稿要求の一部として提出されたjsonに含めました。基本的に私はそこのJSONリクエストに対するCSRF保護をオフにするオプションがあるが、私はむしろそれをしないだろう1 jsonのcsrfトークンを取得して、レールアプリに投稿する

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

params = {:user => {:email => '[email protected]', :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}) 

以下のような迅速な汚いスクリプトを持っています。私は機械化ルートかそれに類するものに行くことができ、CSRFでjsonのリクエストについて心配することはありませんが、私はちょうどrest-clientでこのようなことをして遊びたいと思っています

私はちょうどjsonのリクエストに対してauthenticity_tokenが提供されない理由があります。私がここで取ったかなりハッキーなアプローチよりもトークンの問題を解決する良い方法があるのだろうか。

答えて

8

あなたのアプリケーションに以下のコードを入れてくださいコントローラ:

def verified_request? 
    if request.content_type == "application/json" 
     true 
    else 
     super() 
    end 
end 

before_filterを使用してこのメ​​ソッドを呼び出します。 http://blog.technopathllc.com/2011/09/rails-31-csrf-token-authenticity-for.html

をとRailsでこの問題を確認します:詳細について

がチェック https://github.com/rails/rails/issues/3041

+1

返信いただきありがとうございます。私はCSRFの小切手をオフにするのを避けようとしていましたが、私は推測します。レールがトークンを含んでいないjsonフォームにサービスを提供していますが、トークンをチェックするのはちょっと奇妙なようです。 jsonコンテンツのチェックをオフにするのではなく、トークンを含むjsonフォームを提供するだけで意味がありますか? – Conor

+0

ようこそ...はい、それはCSRFトークンの問題をバイパスするための唯一の方法です。 JSONリクエストでトークンを渡す場合は、ヘッダ:{ 'X-CSRFトークン': '<%= form_authenticity_token.to_s%>' } – swati

+0

チェック:http:// stackoverflowのようなヘッダを使用できます。 com/questions/7203304/warning-cant-verify-csrf-token-authenticity-rails http://stackoverflow.com/questions/8503447/rails-how-to-add-csrf-protection-to-forms-created-in - ジャバスクリプト – swati

0

をごapp/views/products/new.json.jbuilderでは、これを追加します。

json.authenticity_token form_authenticity_token 

これは、値された状態でキー"authenticity_token"を挿入しますトークンは、あなたのjson_responseでもトークンを取得します。アイデアはthis answerです。

関連する問題