Rails 5 has_secure_token加密

问题描述 投票:2回答:1

在Ruby on Rails has_secure_token gem / feature中,它在创建记录时创建一个唯一的令牌,并以纯文本形式存储在数据库中。如果我使用该令牌授予用户访问API的权限,那么将该令牌作为纯文本存储在数据库中是否存在安全风险?

token方法将令牌提交到数据库时,我希望有一种方法可以加密has_secure_token列,类似于bcrypt如何将密码加密到数据库中。

我曾尝试使用像attr_encrypted这样的宝石来存储令牌的散列值,但它似乎与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,我将不胜感激!

如果需要更多信息或者这是令人困惑的,请告诉我。提前致谢!

ruby-on-rails ruby encryption access-token rails-api
1个回答
1
投票

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来加密令牌。

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 = BCryptt::Password.create(api_token, cost: cost)
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.