【问题标题】:Encrypt the Devise token加密设计令牌
【发布时间】:2013-03-20 16:54:00
【问题描述】:

我正在使用带有令牌身份验证的设计,现在,我想加密数据库中的令牌。 谁能给我一个提示,在哪里设计从数据库存储/检索令牌?

我也在使用 attr_encrypted gem,一旦找到正确的位置,整个加密应该相当容易。

编辑:

我已经实现了如下所述的令牌身份验证:http://zyphdesignco.com/blog/simple-auth-token-example-with-devise

我在用户模型中添加了以下行,它应该加密 authentication_token

attr_encrypted :authentication_token, :key => 'a secret key', :attribute => 'authentication_token'

当我运行它并尝试登录时,我收到以下错误消息:

Completed 500 Internal Server Error in 364ms

SystemStackError - stack level too deep:
(gem) actionpack-3.2.13/lib/action_dispatch/middleware/reloader.rb:70:in `'

似乎与 devise 和 attr_encrypted 存在冲突,并且两者都在重新定义 authentication_token 方法(感谢@sbfaulkner 的提示)

也许有人遇到过类似的问题并且知道解决方案?

【问题讨论】:

    标签: devise ruby-on-rails-3.2 attr-encrypted


    【解决方案1】:

    关于 Token Authenticable 策略的重要部分在 Devise::Models:: TokenAuthenticatable module 中 - 它使用一组简单的方法:

    • find_for_token_authentication 用于对资源进行身份验证
    • ensure_authentication_token/ensure_authentication_token! 应该用于为新资源生成令牌 - Devise 不会自己调用它。

    如果attr_encrypted gem 与 A​​R 模型兼容,那么我相信您在使用 Devise 时不会有任何问题,但最好的方法是尝试一下。

    【讨论】:

    • 谢谢卢卡斯!我试图实施一个解决方案,但我遇到了一些麻烦。也许有人可以给我一个提示。我用原始内容创建了 /config/initializers/token_authenticable.rb 然后我尝试添加行 attr_encrypted :authentication_token, :key => 'a secret encryption key', :attribute = > 'authentication_token' 我在启动 rails 服务器时遇到的错误是 /config/initializers/token_authenticatable.rb:44:in <module:TokenAuthenticatable>': undefined method attr_encrypted' for Devise::Models::TokenA uthenticatable:Module (无方法错误)。我被困在这里了。
    【解决方案2】:

    在我的用户模型上,我是这样做的:

    before_save :ensure_authentication_token
    
    attr_encrypted :authentication_token, :key => 'my key'
    
    def ensure_authentication_token
      if authentication_token.blank?
        self.authentication_token = generate_authentication_token
      end
    end
    
    private
    
    def generate_authentication_token
      loop do
        token = User.encrypt_authentication_token(Devise.friendly_token)
        break token unless User.where(encrypted_authentication_token: token).first
      end
    end
    

    秘密就在这个方法中:encrypt_authentication_token attr_encrypted 创建。

    【讨论】:

      猜你喜欢
      • 2016-02-22
      • 2019-07-25
      • 2023-03-04
      • 2014-01-27
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多