在 Ruby on Rails has_secure_token
gem/feature 中,它在记录创建时创建一个唯一的 token ,并将其作为纯文本存储在数据库中。如果我使用该 token 向用户授予对 API 的访问权限,将该 token 作为纯文本存储在数据库中是否存在安全风险?
我希望当 has_secure_token
方法将 token 提交到数据库时,有一种方法可以加密 token
列,类似于 bcrypt
将密码加密到数据库中。
我曾尝试使用诸如 attr_encrypted
之类的 gem 来存储 token 的哈希值,但它似乎与 has_secure_token
不兼容。这是我的模型当前的设置方式:
class User < ApplicationRecord
has_secure_token :token
# attr_encrypted :token, key: :encrypt_token, attribute: 'token'
# def encrypt_token
# SecureRandom.random_bytes(32)
# end
end
注释的代码是attr_encrypted
代码,已被证明是不兼容的。如果有人知道是否有一种方法可以安全地加密数据库中的列,同时还使用 has_secure_token
,我将不胜感激!
如果需要更多信息或这令人困惑,请告诉我。提前致谢!
最佳答案
rails 6 ActiveModel::SecurePassword#has_secure_password接受属性名称参数,并将使用 BCrypt 设置相应 #{attribute}_digest
列的值。默认属性名称是 password
并且模型必须具有 #{attribute}_digest
属性的访问器。
同时包含密码和 api_token 的简化示例:
rails generate model User password_digest:string api_token_digest:string
rails 6
class User < ApplicationRecord
has_secure_password #create a `password` attribute
has_secure_password :api_token, validations: false
before_create do
self.reset_token = SecureRandom.urlsafe_base64
end
end
在 Rails 6 之前,您可以直接调用 BCrypt 来加密 token 。
require 'bcrypt'
class User < ApplicationRecord
has_secure_password #create a `password` attribute
before_create do
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
self.api_token = SecureRandom.urlsafe_base64
self.api_token_digest = BCrypt::Password.create(api_token, cost: cost)
end
end
关于ruby-on-rails - Rails 5 has_secure_token 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48193785/