如何关闭仅适用于JSON的railsprotect_from_forgery过滤器 [英] How to turn off rails protect_from_forgery filter only for json
问题描述
我有一个用Rails3构建的网站,现在我想实现JSON API来访问移动客户端.但是,由于protect_from_forgery筛选器,从客户端发送json发布请求.因为客户端不会从服务器检索任何数据,所以客户端无法接收auth_token,所以我只想对json请求关闭protect_from_forgery选项(我以为rails3在默认情况下会这样做,但显然不会)
I have web site built with Rails3 and now I want to implement json API for mobile client access. However, sending json post request from the client because of the protect_from_forgery filter. Because the client will not retrieve any data from the server, there is no way that the client can receive auth_token so I would like to turn off the protect_from_forgery option only for json requests (I thought rails3 does this in default but apparently it does not).
我知道在此处中讨论了类似的话题,但在这种情况下,他在发送发布请求之前收到auth_token.
I know similar topic is discussed at here but in that case, he receives auth_token before sending post request.
所以我的问题是仅对json关闭protect_from_forgery是这样做的好方法吗?如果是,该怎么办?如果没有,那有什么选择呢?
So my question is turning off the protect_from_forgery only for json is good way of doing this? If yes, how to do so? If no, what is the alternative?
仅供参考,我使用以下ajax请求
FYI, I use following ajax request
$.ajax({
type: 'POST',
url: "http://www.example.com/login.json",
data: { 'email': emailVal, 'password': passwordVal },
success: onSuccess,
error: onError,
dataType: "json"
});
我收到ActionController :: InvalidAuthenticityToken错误.
and I get ActionController::InvalidAuthenticityToken error.
顺便说一句,下面的curl命令虽然可以工作...
curl -H内容类型:应用程序/json" -c cookies.txt -d'{电子邮件":emailVal,密码":passwordVal}'-X POST
By the way, following curl command works though...
curl -H "Content-Type: application/json" -c cookies.txt -d '{"email": emailVal, "password": passwordVal}' -X POST http://www.example.com/login.json -i
推荐答案
看看这篇文章: archive.org ]
Take a look at this post: http://zadasnotes.blogspot.com/2010/11/rails-3-forgery-csrf-protection-for.html [archive.org]
更新
此后,该文章已被删除,因此我进行了快速搜索,发现该文章的原始作者在SO上发布了此问题.
The article has been removed since then, so I did a quick search and I found the original author of the article posting this question on SO.
这篇关于如何关闭仅适用于JSON的railsprotect_from_forgery过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!