使用Rails存储加密的Cookie [英] Storing an encrypted cookie with Rails

查看:202
本文介绍了使用Rails存储加密的Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Rails中的一个cookie中存储一小块数据(小于10个字符),我需要它来确保安全。我不想让任何人能够读取该数据或注入他们自己的数据(因为这将打开应用程序的各种攻击)。我认为加密cookie的内容是去的方式(我应该也签名?)。什么是最好的方法?

I need to store a small piece of data (less than 10 characters) in a cookie in Rails and I need it to be secure. I don't want anybody being able to read that piece of data or injecting their own piece of data (as that would open up the app to many kinds of attacks). I think encrypting the contents of the cookie is the way to go (should I also sign it?). What is the best way to do it?

现在我做这个,看起来很安全,但许多事情看起来比我知道的更多的人安全安全,然后发现它不是真的安全。

Right now I'm doing this, which looks secure, but many things looked secure to people that knew much more than I about security and then it was discovered it wasn't really secure.

我以这种方式保存秘密:

I'm saving the secret in this way:

encryptor = ActiveSupport::MessageEncryptor.new(Example::Application.config.secret_token)
cookies[:secret] = {
  :value => encryptor.encrypt(secret),
  :domain => "example.com",
  :secure => !(Rails.env.test? || Rails.env.development?)
}

然后我读这样:

encryptor = ActiveSupport::MessageEncryptor.new(Example::Application.config.secret_token)
secret = encryptor.decrypt(cookies[:secret])

安全?更好的方法吗?

更新:我知道Rails的会话和它的安全,通过签署cookie和可选地存储会话服务器侧的内容,并且我使用会话用于它。但我的问题是关于存储一个cookie,一个我不想在会话中的信息,但我仍然需要它是安全的。

Update: I know about Rails' session and how it is secure, both by signing the cookie and by optionally storing the contents of the session server side and I do use the session for what it is for. But my question here is about storing a cookie, a piece of information I do not want in the session but I still need it to be secure.

推荐答案

我重新发布 JacobM 的答案,他已删除,因为这是正确答案并指出我的方向正确。如果他取消删除它,我将删除这个,并选择他作为最好的答案。

I'm re-posting JacobM's answer, that he deleted, because it was the correct answer and pointed me in the right direction. If he undeletes it, I'll delete this one and pick his as the best answer.


首先,如果使用 encrypt_and_verify 而不是 encrypt ,它将
为您签名cookie。

First of all, if you use encrypt_and_verify instead of encrypt it will sign the cookie for you.

然而,当涉及到安全性,我总是喜欢依赖于已经公开审查的
解决方案,而不是滚动我自己。
例如 encrypted-cookies gem

However, when it comes to security, I always prefer to rely on solutions that have been vetted in public, rather than rolling my own. An example would be the encrypted-cookies gem.

这篇关于使用Rails存储加密的Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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