我发送电子邮件地址作为signed cookie:
cookies.signed[:user_email] = { value: user.email, expires: 24.hours.from_now }
稍后,前端将其作为HTTP header 发送回给我:
request.headers["HTTP_USER_EMAIL"]
然后如何从接收的 header 解密到原始电子邮件地址? 我尝试了下面的行,但是会产生错误:
NoMethodError Exception: undefined method `signed' for #String:0x00000008a57a78
email = request.headers["HTTP_USER_EMAIL"].signed unless (request.headers["HTTP_USER_EMAIL"] == nil)
使用
debugger
,我得到request.headers["HTTP_USER_EMAIL"]
的"Im9yZ29utcGxlLmNvbSI=--37ddc725d139f86095ae839012c31a14e"
值。因此,存在加密的值。Cookie与 header 之间的差值:如果可以在cookie中找到加密的值,则可以使用
cookies.signed[:http_user_email]
对其进行解密。我对request.headers["HTTP_USER_EMAIL"].signed
和request.headers.signed["HTTP_USER_EMAIL"]
的尝试与使用cookie时的尝试基本相同,您将获取cookie的加密值并在末尾添加.signed:"Im9yZ29utcGxlL".signed
。那也不行。但是,如果在字符串中找到加密的值,该怎么办?还是您认为不需要使用用户电子邮件地址的加密版本进行API身份验证?基于电子邮件地址和 token 的组合进行身份验证( token 需要与摘要( token 的加密版本)匹配)。
最佳答案
在config/initializers/secret_token.rb
处,您应该具有密码:
Demo::Application.config.secret_key_base = 'b14e9b5b720f84fe02307ed16bc1a32ce6f089e10f7948422ccf3349d8ab586869c11958c70f46ab4cfd51f0d41043b7b249a74df7d53c7375d50f187750a0f5'
解密:
content = request.headers["HTTP_USER_EMAIL"]
unescaped_content = URI.unescape(content)
crypt = ActiveSupport::MessageEncryptor.new(Rails.configuration.secret_key_base)
data = crypt.decrypt_and_verify(unescaped_content)
在4.0中基于默认配置。
从4.1开始,您可以使用config/secrets.yml而不是secret_token.rb
关于ruby-on-rails - 当在HTTP header 而不是cookie中找到加密值时,如何解密 `.signed`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34967576/