【发布时间】:2020-01-21 14:56:43
【问题描述】:
我正在尝试解密签名的 cookie,但没有成功。
我在会话控制器中使用签名 cookie 的方式是这样的
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
if params[:remember_me]
cookies.signed[:auth_token] = { value: user.auth_token, expires: 2.weeks.from_now }
else
cookies.signed[:auth_token] = user.auth_token
end
redirect_to root_url, notice: "Logged in!"
else
flash.now.alert = "Email or password is invalid"
render :new
end
end
def destroy
cookies.delete(:auth_token)
redirect_to root_url, notice: 'Logged Out'
end
end
现在在应用程序控制器端,我正在尝试解密它
require 'cgi'
require 'active_support'
class ApplicationController < ActionController::Base
protect_from_forgery
def current_user
@current_user ||= User.find_by(auth_token: verify_and_decrypt)
end
def verify_and_decrypt
config = Rails.application.config
cookie = CGI::unescape(cookies[:auth_token])
salt = config.action_dispatch.authenticated_encrypted_cookie_salt
encrypted_cookie_cipher = config.action_dispatch.encrypted_cookie_cipher || 'aes-256-gcm'
serializer = ActiveSupport::MessageEncryptor::NullSerializer
key_generator = ActiveSupport::KeyGenerator.new(Rails.application.secret_key_base, iterations: 1000)
key_len = ActiveSupport::MessageEncryptor.key_len(encrypted_cookie_cipher)
secret = key_generator.generate_key(salt, key_len)
encryptor = ActiveSupport::MessageEncryptor.new(secret, cipher: encrypted_cookie_cipher, serializer: serializer)
cookie = encryptor.decrypt_and_verify(cookie)
cookie
end
end
但每次在这条线上失败时 cookie = encryptor.decrypt_and_verify(cookie)
ActiveSupport::MessageEncryptor::InvalidMessage: ActiveSupport::MessageEncryptor::InvalidMessage
from /home/anikettiwari/.rvm/gems/ruby-2.5.3/gems/activesupport-5.2.4.1/lib/active_support/message_encryptor.rb:190:in `_decrypt'
谁能告诉我我做错了什么
对于参考我检查了这个link
【问题讨论】:
-
如果您仅在创建它们的同一应用程序中使用这些 cookie,则无需“手动”解密它们。只需使用
cookies.signed[:auth_token]也可以访问ApplicationController中的原始值。 -
为什么这里不需要解密?
-
因为 Rails 在使用
cookies.signed[:auth_token]访问 cookie 值时会自动执行此操作(相比之下,cookies[:auth_token]将为您提供原始值)。就像您在SessionsController中设置 cookie 值时,它会自动序列化、签名和加密原始值一样。 -
@HolgerJust 感谢您的描述
标签: ruby-on-rails ruby cookies ruby-on-rails-5.2