问题描述
如何检索CSRF令牌以通过JSON请求?
How can I retrieve the CSRF token to pass with a JSON request?
我知道为安全起见建议
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]]];
这篇关于导轨 - “警告:无法验证CSRF令牌真实性”为json设计请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!