【问题标题】:Password encryption problem in Rails Devise gemRails Devise gem中的密码加密问题
【发布时间】:2010-08-16 09:42:12
【问题描述】:

我现在更改为使用 Gem Devise 进行用户身份验证。但是不知道怎么匹配加密!

我知道我们可以编写一个新的加密器并在初始化器中分配它,但关键是加密器只接受 4 个参数(密码、延伸、盐、胡椒)。但就我而言,我确实在加密中包含了用户的电子邮件和自定义盐。

是否可以将用户的电子邮件和自定义盐传递到加密器中?

ps。我正在使用 database_authenticable

【问题讨论】:

  • 为什么要包含电子邮件和自定义盐而不是使用标准方式?
  • 这是很久以前的事了,如果我没记错的话,我在更改设计之前的加密使用了另一种盐的电子邮件。因此,为了不影响用户,我们必须微调设备的加密,使其给出与原始结果相同的结果。

标签: ruby-on-rails gem devise


【解决方案1】:

很遗憾没有人回答我的问题......

不过,我想我已经找到了答案,虽然它没有我想象的那么漂亮。

首先,在初始化器中创建加密类:

module Devise
  module Encryptors
    class MySha1 < Base
      def self.digest(password, salt)
        Digest::SHA1.hexdigest("#{salt}-----#{password}")
      end

      def self.salt(email)
        Digest::SHA1.hexdigest("#{Time.now}-----#{email}")
      end
    end
  end
end

其次,覆盖User模型中的一些方法:

# overwrite this method so that we call the encryptor class properly
def encrypt_password
  unless @password.blank?
    self.password_salt = self.class.encryptor_class.salt(email)
    self.encrypted_password = self.class.encryptor_class.digest(@password, self.password_salt)
  end
end

# Because when the database_authenticatable wrote the following method to regenerate the password, which in turn passed incorrect params to the encrypt_password, these overwrite is needed!
def password=(password)
  @password = password
end
def password_digest(pwd)
  self.class.encryptor_class.digest(pwd, self.password_salt)
end

最后,我们必须教导何时加密密码:

before_save :encrypt_password

【讨论】:

    【解决方案2】:

    我不确定它的年龄,但这似乎是一种更好的支持方式:http://presentations.royvandewater.com/authentication-with-devise.html#9

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 2015-06-20
      • 2013-02-05
      相关资源
      最近更新 更多