8

私が書いたレールアプリにアクセスするために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 リクエストに対して提供されない理由があるかどうかを知りたいだけだと思います。また、ここで取ったかなりハックなアプローチよりもトークンの問題を解決するより良い方法があるかどうかも疑問に思っています。

4

2 に答える 2

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を確認してください。

レールでこの問題を確認してください: https://github.com/rails/rails/issues/3041

于 2012-05-02T13:01:33.870 に答える
2

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

json.authenticity_token form_authenticity_token

"authenticity_token"これにより、値がトークンであるキーが挿入されるjson_responseため、トークンも取得します。この回答からのアイデア。

于 2016-08-28T01:25:49.620 に答える