Rails 使用移动应用程序来保护免受伪造
我正在 Rails 上构建一个应用程序,并且我的 application.rb
中有 protect_from_forgery
。我还为移动应用程序构建了一个 RESTful API,以便使用 JSON
数据进行通信。我看到一些网站声称,为了让移动应用程序与 Rails 应用程序交互,他们关闭了 JSON 请求的 protect_from_forgery
。
这如何解决CSRF问题?恶意网站不能有代表用户执行不需要的更改的 JSON POST 请求吗?
因此,为了解决这个问题,我决定使用自定义的mime-type
或者只有移动应用程序才会使用的特殊密钥
,然后使用protect_from_forgery
执行以下操作:
- 检查 csrf 令牌是否作为
hidden div
出现(对于 Web 应用程序为 true,默认情况下包含)。 - 如果不存在,请检查此
特殊密钥
或mime-type
。
有没有办法实现这个或类似的来解决这个问题?
更新
原来是我想多了。 Rails 是“神奇的”,它以某种方式自动且适当地处理来自移动应用程序的请求,而不会引发异常。所以,本质上我们根本不需要做任何修改。
我并没有完全检查 Rails 是如何实现这一点的——从教学角度来说,这对于某些人来说可能仍然很有趣。
I am building an app on Rails and I have the protect_from_forgery
in my application.rb
. I have also built a RESTful API for mobile apps to communicate with using JSON
data. I see some sites that claim that in order for the mobile app to interact with the rails application, they turn off protect_from_forgery
for JSON requests.
How does this solve the problem of CSRF? Can a malicious site not have JSON POST request that performs undesirable changes on behalf of the user?
So, to solve this problem , I decided to use a custom mime-type
or perhaps a special key
that only the mobile app would use, and then have protect_from_forgery
perform the following:
- Check if the csrf token is present as a
hidden div
(true for the web app and included by default). - If not present, check for this
special key
ormime-type
.
Is there anyway to achieve this, or similar, to counter this problem?
Update
It turns out that I had over-thought the problem. Rails is "magical" and somehow handled requests coming from a mobile app automatically and appropriately without raising an exception. So, essentially we didn't have to make any modifications at all.
I didn't quite check how Rails achieves this though - pedagogically speaking, this might still be interesting to know for some.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不必使用 ActiveResources。如果您以 xml 形式发送请求,那么它将绕过 protected_from_forgery。
它应该非常简单。
You don't have to use ActiveResources. If you send your request as xml then it'll bypass the protect_from_forgery.
It should be pretty straightforward.