如何仅针对 json 关闭 Rails Protect_from_forgery 过滤器
我有使用 Rails3 构建的网站,现在我想实现 json API 以用于移动客户端访问。但是,由于 protected_from_forgery 过滤器,从客户端发送 json post 请求。因为客户端不会从服务器检索任何数据,所以客户端无法接收 auth_token 所以我想仅针对 json 请求关闭 protected_from_forgery 选项(我认为rails3默认会这样做,但显然它没有) 。
我知道此处讨论了类似的主题,但在这种情况下,他会收到 auth_token在发送 post 请求之前。
所以我的问题是仅针对 json 关闭 protected_from_forgery 是这样做的好方法吗?如果是,该怎么做?如果不是,还有什么替代方案?
仅供参考,我使用以下 ajax 请求
$.ajax({
type: 'POST',
url: "http://www.example.com/login.json",
data: { 'email': emailVal, 'password': passwordVal },
success: onSuccess,
error: onError,
dataType: "json"
});
,并收到 ActionController::InvalidAuthenticityToken 错误。
顺便说一下,下面的curl命令是有效的......
curl -H "Content-Type: application/json" -c cookies.txt -d '{"email": emailVal, "password": passwordVal}' -X POST http://www.example.com/login.json -i
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).
I know similar topic is discussed at here but in that case, he receives auth_token before sending post request.
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?
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"
});
and I get ActionController::InvalidAuthenticityToken error.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在表单中传递authenticity_token字段,而不是禁用CSRF检查,例如:
http://apidock.com/rails/v2.0.0/ActionController/RequestForgeryProtection/ClassMethods/protect_from_forgery
Instead of disabling the CSRF check you can pass the authenticity_token field in your forms, eg:
http://apidock.com/rails/v2.0.0/ActionController/RequestForgeryProtection/ClassMethods/protect_from_forgery
如果是 json 请求,您可以跳过真实性令牌检查
You can just skip the authenticity token check if its a json request
将以下代码添加到您的
./app/controllers/application_controller.rb
中:Add the code below to your
./app/controllers/application_controller.rb
: