加密Devise令牌

问题描述:

我正在使用Devise和令牌认证,现在我想加密数据库中的令牌。 任何人都可以给我一个提示,其中设计从数据库中存储/检索令牌吗?加密Devise令牌

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

编辑:

喜欢在这里描述我已经实现令牌认证: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 `' 

似乎有是制定一个冲突和attr_encrypted和两个战斗在authentication_token方法的重新定义(THX的提示@sbfaulkner)

也许有人有类似的问题,并且知道解决的办法?

有关令牌真伪战略的重要位在Devise::Models:: TokenAuthenticatable module - 它用一套简单的方法的工作原理:

  • find_for_token_authentication用于验证
  • ensure_authentication_token/ensure_authentication_token!应采用资源为新鲜资源生成一个令牌 - Devise不会自己调用它。

如果0123mgem与AR模型兼容,那么我相信你不会有任何Devise问题,但最好的方法是确定它。

+0

谢谢卢卡斯! 我试图实施一个解决方案,但我遇到了一些麻烦。也许有人可以给我一个提示。 我用原始内容创建了**/config/initializers/token_authenticable.rb **,然后尝试添加以下行** attr_encrypted:authentication_token,:key =>'一个秘密加密密钥',:attribute =>' authentication_token'** 启动rails服务器时出现的错误是**/config/initializers/token_authenticatable.rb:44:在中:undefined方法attr_encrypted为Devise :: Models :: TokenA uthenticatable:模块(NoMethodError)**。 我被困在这里。 – 2013-04-03 12:28:17

这里是我做到了,我的用户模型:

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创建。