How do I customize the length of the token generated in :token_authenticatable in devise - Rails 3?

て烟熏妆下的殇ゞ 提交于 2020-01-03 03:36:09

问题


My token generated seems to be about 20 characters, how do I change the length to something else ?

I checked the devise.rb file and tried both:

config.token_authentication_key = :access_key    
config.token_authenticatable.length = 40

produced this error:

config/initializers/devise.rb:110:in `block in <top (required)>': undefined method `token_authenticatable' for Devise:Module (NoMethodError)

and

config.token_authentication_key = :access_key
config.token_authentication_key.length = 40

produced this error:

/config/initializers/devise.rb:110:in `block in <top (required)>': undefined method `length=' for :access_key:Symbol (NoMethodError)

and both gave me errors when I tried to run the console.

Is there anyway to do this ?


回答1:


Devise does not provide a functionality to set the length of this token. You would have to override the generate_token method on your model to change the outcome of this token.




回答2:


I achieved changing the reset_token_password length overriding the friendly_token method. For example:

module Devise def self.friendly_token(_length = 20) SecureRandom.urlsafe_base64(5).tr('lIO0', 'sxyz') end end

(Remember that the tokens are hashed in the db so even though you successfully set a shorter code if you do user.reset_password_token you will see a long code which is the hashed token, not the real one.)



来源:https://stackoverflow.com/questions/5534836/how-do-i-customize-the-length-of-the-token-generated-in-token-authenticatable-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!