2013-03-20 56 views
1

我正在使用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)

也許有人有類似的問題,並且知道解決的辦法?

回答

0

有關令牌真僞戰略的重要位在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

0

這裏是我做到了,我的用戶模型:

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