跳至内容 跳至搜索

ActiveRecord 签名 ID

命名空间
方法
S

类公共方法

signed_id_verifier_secret

在 Rails 外部使用 ActiveRecord 时,设置用于签名 ID 验证器实例的密钥。在 Rails 中,这会使用 Rails 应用程序密钥生成器自动设置。

# File activerecord/lib/active_record/signed_id.rb, line 13
class_attribute :signed_id_verifier_secret, instance_writer: false

实例公共方法

signed_id(expires_in: nil, expires_at: nil, purpose: nil)

返回使用预先配置的 ActiveSupport::MessageVerifier 实例生成的签名 ID。此签名 ID 防篡改,因此可以安全地通过电子邮件发送或与外部世界共享。此外,还可以将其设置为过期(默认情况下不设置过期),并按特定用途缩小范围。如果在调用 find_signed 之前已超过过期日期,则 ID 不会找到指定的记录。如果设置了用途,则也必须匹配此用途。

如果您意外地泄露了签名 ID,并且希望在过期日期之前撤回(或者您可能忘记设置过期日期!),可以使用用途对 signed_id 进行版本控制,如下所示

user.signed_id purpose: :v2

然后,您将 find_signed 调用更改为需要此新用途。不再使用此用途创建的任何旧签名 ID 都将找不到记录。

# File activerecord/lib/active_record/signed_id.rb, line 112
def signed_id(expires_in: nil, expires_at: nil, purpose: nil)
  raise ArgumentError, "Cannot get a signed_id for a new record" if new_record?

  self.class.signed_id_verifier.generate id, expires_in: expires_in, expires_at: expires_at, purpose: self.class.combine_signed_id_purposes(purpose)
end