3

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.

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
Xodarap
  • 11,581
  • 11
  • 56
  • 94
  • I don't find any `secret_token.rb`. Which version of Rails you are using? – Pavan Jun 17 '15 at 05:22
  • @Pavan: according to [this answer](http://stackoverflow.com/a/23124507/347165) that file is used for rails 3 and 4 and was deprecated for 4.1. But I have the analogous question for `secrets.yml` – Xodarap Jun 17 '15 at 15:16

1 Answers1

4

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.

oxfist
  • 749
  • 6
  • 22