关闭Rails 3中的CSRF令牌

114
我有一个Rails应用程序,为iPhone应用程序提供一些API。我希望能够简单地在资源上发布而不必担心获取正确的CSRF令牌。我尝试了一些在stackoverflow中看到的方法,但似乎它们在Rails 3中不再起作用。
谢谢你的帮助。
3个回答

200

在您想要禁用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请求伪造保护


2
这是适用于同时具有常规浏览器可访问表单和API端点的应用程序的正确答案。如果您绝对确定您的应用程序不会有任何浏览器可访问表单,则 Markus Proske 的答案是正确的。 - Asfand Qazi
这个应该放在哪里?如果是某个 gem 的控制器部分呢? - Throw Away Account
我可以问一下你是否能回答这个非常相似的问题吗?https://dev59.com/8FUL5IYBdhLWcg3wjIpQ - user4412054

108

Rails 3中,您可以在控制器中禁用特定方法的CSRF令牌:

protect_from_forgery :except => :create 

12
提醒读者注意,以下内容应该放在 ApplicationController 中。Mike Lewis 在下面的回复中提到的 skip_before_filter :verify_authenticity_token 是如何在每个控制器上禁用它的,假设该控制器继承自 ApplicationController - NudeCanalTroll
似乎这是不安全的 https://dev59.com/KmTVa4cB1Zd3GeqP_Q1f。你认为呢?是吗? - sites
@NudeCanalTroll,你的意思是将它放到我想要的控制器中不起作用吗? - DivinesLight
我可以问一下你是否能回答这个非常相似的问题吗?https://dev59.com/8FUL5IYBdhLWcg3wjIpQ - user4412054

33

在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

1
有什么区别? - Adam D. Ruppe
我可以问一下你是否能回答这个非常相似的问题吗?https://dev59.com/8FUL5IYBdhLWcg3wjIpQ - user4412054
John Sam,等我有时间了我会尽力去做的。 - thank_you

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接