2012-05-02 17 views
8

我一直在玩使用rest-client來訪問我寫的rails應用程序。我已經編寫了一個快速腳本來登錄併發出發布請求。一切正常,但我確實必須解決這個事實,即如果您在json中爲表單提出請求,則不會提供authenticity_token。我不得不在其他的一個請求中獲取authenticity_token,然後把它包含在我作爲我的post請求的一部分提交的json中。基本上我有一個快速的髒腳本像下面獲得csrf標記的json發佈的請求到rails應用程序

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請求的選項,但我寧願不這麼做。我可以去機械化路線或類似的東西,然後我不會擔心與CSRF的JSON請求,但我只是想玩弄這個東西與休息客戶端

我想我只是想知道如果有沒有爲json請求服務authenticity_token的原因,我也想知道是否有更好的方法來解決令牌問題比我在這裏採取的漂亮hacky方法

回答

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

+1

感謝您的回覆swati,它看起來很有用。我想盡管我試圖避免關閉CSRF檢查。對我來說,看起來有點奇怪,rails會提供不包含任何令牌的json表單,但會檢查令牌。僅僅通過包含令牌來提供json表單而不是關閉json內容檢查是否合理? – Conor

+0

歡迎...是的,這是繞過CSRF令牌問題的唯一途徑。如果您想要將令牌與您的JSON請求一起傳遞,可以使用如下頭部:頭文件:{X = CSRF-Token':'<%= form_authenticity_token.to_s%>' } – swati

+0

check: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 -javascript – swati

0

在你app/views/products/new.json.jbuilder,補充一點:

json.authenticity_token form_authenticity_token 

這將插入一個關鍵"authenticity_token"與價值感令牌,所以在你的json_response你也得到了令牌。來自this answer的想法。

相關問題