Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need both devise and rails secret keys?

Inside config/initializers there is secret_token.rb and devise.rb, both of which have a slot to enter a secret key. For devise its config.secret_key and for rails it is Application.config.secret_key_base.

Do I need both of these things to be set? I don't understand which secret keys control which behaviors.

like image 877
Xodarap Avatar asked Oct 21 '25 13:10

Xodarap


1 Answers

I struggled with this at first too. It's not really that clearly explained in the docs.

Devise usage of Secret Key

From the Devise repository:

initializer "devise.secret_key" do |app|
  if app.respond_to?(:secrets)
    Devise.secret_key ||= app.secrets.secret_key_base
  elsif app.config.respond_to?(:secret_key_base)
    Devise.secret_key ||= app.config.secret_key_base
  end

  Devise.token_generator ||=
    if secret_key = Devise.secret_key
      Devise::TokenGenerator.new(
        ActiveSupport::CachingKeyGenerator.new(ActiveSupport::KeyGenerator.new(secret_key))
      )
    end
end

From the code above, once Devise.secret_key is assigned a value, it is then used to generate a token, which is also used for several Devise functionalities such as account confirmation, resetting passwords and unlocking accounts. All of these require a token, and that token by the code shown above.

Then from the configuration file devise.rb:

# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
# Devise will use the `secret_key_base` as its `secret_key`
# by default. You can change it below and use your own secret key.

This means you don't need to set or create a separate secret_key for Devise to work. If you already have a secret_key_base set, as explained in the comments above, then Devise's `secret_key' will just default to that.

I personally just commented out the code, but you're free to even delete the line that assigns config.secret_key.

Rails usage of Secret Key

secret_key_base is used for signing and encrypting cookies, and it's very well explained in this answer.

like image 169
oxfist Avatar answered Oct 23 '25 06:10

oxfist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!