2011-04-14 53 views
82

我有一個rails應用程序,它爲iPhone應用程序提供一些apis服務。 我希望能夠簡單地發佈資源,而不必考慮獲取正確的csrf標記。 我嘗試了一些方法,我在這裏看到的計算器,但它似乎他們不再工作的軌道3. 謝謝你幫助我。在rails 3中關閉CSRF令牌

回答

132

在控制器要禁用CSRF檢查:

skip_before_action :verify_authenticity_token 

或者禁用它的一切,除了幾個方法:

skip_before_action :verify_authenticity_token, :except => [:update, :create] 

,或禁用只有指定的方法:

skip_before_action :verify_authenticity_token, :only => [:custom_auth, :update] 

更多信息:RoR Request Forgery Protection

+1

這對於那些有定期的瀏覽器訪問的形式和API端點的混合應用程序的正確答案。 Markus Proske的回答是正確的,如果你確定你的應用程序中沒有任何瀏覽器可訪問的表單。 – 2014-07-09 10:44:46

+0

這究竟在哪裏呢?如果某些寶石的控制器部分怎麼辦? – 2017-04-05 08:29:23

102

在Rails3中,你可以在你的控制器的具體方法禁用CSRF令牌:

protect_from_forgery :except => :create 
+12

對於任何人閱讀,請注意這是'ApplicationController'應該去的。 Mike Lewis的回答如下('skip_before_filter:verify_authenticity_token')是如何在每個控制器的基礎上禁用它,假設控制器繼承自'ApplicationController'。 – NudeCanalTroll 2013-02-16 21:04:54

+0

似乎這是不安全的http://stackoverflow.com/questions/10676018/security-safe-to-disable-csrf-tokens-for-json-rails-calls。你怎麼看?是嗎? – juanpastas 2013-05-13 03:49:08

+0

@NudeCanalTroll你的意思是把它放在控制器,我想它不會工作? – BlackDivine 2013-05-28 10:27:15

28

使用Rails 4,你現在有skip_before_action而不是skip_before_filter寫的選項。

# Works in Rails 4 and 5 
skip_before_action :verify_authenticity_token 

# Works in Rails 3 and 4 (deprecated in Rails 4 and removed in Rails 5) 
skip_before_filter :verify_authenticity_token 
+0

有什麼區別? – 2015-02-25 13:49:18

+5

如果我沒有記錯,過濾器已被棄用 – nruth 2015-04-03 22:02:38