2011-07-01 36 views
0

當我在我的一個Rails控制器中調用某個方法時,我想檢查用戶的IP地址是否在可信列表中,如果是,請覆蓋request.forgery_whitelisted?方法是正確的,以便CSRF保護不被執行。Overiding request.forgery_whitelisted?

我讀過的博客文章似乎表明,在控制器操作中聲明以下內容可以實現此目的,但仍會引發CSRF保護錯誤。

if request.remote_ip = "127.0.0.1" 
def request.forgery_whitelisted?; true; end 
end 

有沒有別的地方,這需要發生,以覆蓋的方法及早爲它生效?

回答

1

下列任一應工作:

  • 覆蓋/猴子補丁'verify_authenticity_token的方法在你的ApplicationController:

def verify_authenticity_token 
    super unless request.remote_ip = '127.0.0.1' # TODO: replace this with actual white-listing logic 
end 
  • 猴子補丁'forgery_whitelisted?方法:

module ActionDispatch 
    class Request 
    def forgery_whitelisted? 
     super if remote_ip == '127.0.0.1' # TODO: replace this with actual white-listing logic 
    end 
    end 
end