导轨 - “警告:无法验证CSRF令牌真实性”为json设计请求 [英] rails - "WARNING: Can't verify CSRF token authenticity" for json devise requests

查看:93
本文介绍了导轨 - “警告:无法验证CSRF令牌真实性”为json设计请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检索CSRF令牌以通过JSON请求?

How can I retrieve the CSRF token to pass with a JSON request?

我知道为安全起见.org / 2011/2/8 / csrf-protection-bypass-in-ruby-on-rails

I know that for security reasons Rails is checking the CSRF token on all the request types (including JSON/XML).

我可以放入我的控制器 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


使用< ;%= form_authenticity_token%>

问题是如何?我需要首先调用我的任何页面来检索令牌,然后用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设计请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆