问题描述
如何检索 CSRF 令牌以通过 JSON 请求传递?
How can I retrieve the CSRF token to pass with a JSON request?
我知道出于安全原因Rails 正在检查所有请求类型(包括 JSON/XML)上的 CSRF 令牌.
我可以放入我的控制器 skip_before_filter :verify_authenticity_token
,但我会失去 CRSF 保护(不建议:-)).
I could put in my controller skip_before_filter :verify_authenticity_token
, but I would lose the CRSF protection (not advisable :-) ).
这个类似的(仍然不被接受)answer建议
This similar (still not accepted) answer suggests to
使用
问题是如何?我是否需要首先调用我的任何页面以检索令牌,然后使用 Devise 进行真正的身份验证?或者它是一种一次性信息,我可以从我的服务器获取然后一直使用(直到我在服务器上手动更改它)?
The question is how? Do I need to do a first call to any of my pages to retrieve the token and then do my real authentication with Devise? Or it is an information one-off that I can get from my server and then use consistently (until I manually change it on the server itself)?
推荐答案
编辑:
在 Rails 4 中,我现在使用@genkilabs 在下面评论中的建议:
In Rails 4 I now use what @genkilabs suggests in the comment below:
protect_from_forgery with: :null_session, if: Proc.new { |c|c.request.format == 'application/json' }
这不是完全关闭内置安全性,而是在没有 CSRF 令牌的情况下击中服务器时终止可能存在的任何会话.
Which, instead of completely turning off the built in security, kills off any session that might exist when something hits the server without the CSRF token.
skip_before_filter :verify_authenticity_token, :if =>proc.new { |c|c.request.format == 'application/json' }
这将关闭对已正确标记为此类的 json 帖子/放置的 CSRF 检查.
This would turn off the CSRF check for json posts/puts that have properly been marked as such.
例如,在 iOS 中,将以下内容设置为您的 NSURLRequest,其中参数"是您的参数:
For example, in iOS setting the following to your NSURLRequest where "parameters" are your parameters:
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json"
forHTTPHeaderField:@"content-type"];
[request setValue:@"application/json"
forHTTPHeaderField:@"accept"];
[request setHTTPBody:[NSData dataWithBytes:[parameters UTF8String]
length:[parameters length]]];
这篇关于rails - “警告:无法验证 CSRF 令牌的真实性";用于 json 设计请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!