在 Rails 6 上定义 secret_key_base 的正确方法是什么?

Mar*_*lva 8 ruby-on-rails ruby-on-rails-6

secret_key_base既然我们拥有每个环境的凭据,那么在 Rails 6上定义的正确方法是什么?

我的环境有这个变量,SECRET_KEY_BASE但 Rails 没有找到它。我尝试定义secret_key_baseconfig\credentials\production.yml.enc但它对Rails.application.credentials.secret_key_base

我知道config/secrets.yml

staging:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
Run Code Online (Sandbox Code Playgroud)

有效,但是,那是 Rails 6 的方式吗?

Mar*_*lva 16

secret_key_baseRails 6 中访问和检查的正确方式不再是:~

Rails.application.credentials.secret_key_base
Run Code Online (Sandbox Code Playgroud)

现在是:

Rails.application.secret_key_base
Run Code Online (Sandbox Code Playgroud)

我不确定这是 Rails 6 还是一直这样。在查看此方法及其实现时,这一点变得非常清楚:

https://github.com/rails/rails/blob/09a2979f75c51afb797dd60261a8930f84144af8/railties/lib/rails/application.rb#L410-L427

# The secret_key_base is used as the input secret to the application's key generator, which in turn
# is used to create all MessageVerifiers/MessageEncryptors, including the ones that sign and encrypt cookies.
#
# In development and test, this is randomly generated and stored in a
# temporary file in <tt>tmp/development_secret.txt</tt>.
#
# In all other environments, we look for it first in ENV["SECRET_KEY_BASE"],
# then credentials.secret_key_base, and finally secrets.secret_key_base. For most applications,
# the correct place to store it is in the encrypted credentials file.
def secret_key_base
  if Rails.env.development? || Rails.env.test?
    secrets.secret_key_base ||= generate_development_secret
  else
    validate_secret_key_base(
      ENV["SECRET_KEY_BASE"] || credentials.secret_key_base || secrets.secret_key_base
    )
  end
end
Run Code Online (Sandbox Code Playgroud)

开发模式和测试模式都有自己的生成和存储密钥库的方式。对于其他所有内容,它会按顺序从环境、凭据或机密中提取出来。