如何使用secrets.yml在Rails 4.1中动态生成秘密令牌?

And*_*eas 7 security ruby-on-rails ruby-on-rails-4

新的铁路.按照Hartl的教程,他使用此代码动态生成config/initializers/secret_token.rb的秘密令牌

require 'securerandom'

def secure_token
  token_file = Rails.root.join('.secret')
  if File.exist?(token_file)
    # Use the existing token.
    File.read(token_file).chomp
  else
    # Generate a new token and store it in token_file.
    token = SecureRandom.hex(64)
    File.write(token_file, token)
    token
  end
end

SampleApp::Application.config.secret_key_base = secure_token
Run Code Online (Sandbox Code Playgroud)

我试图通过使用secrets.yml来遵循新的Rails 4.1方式,并删除secret_token.rb:

development:
  secret_key_base: 79c1389c2fadc5a5a1918a5104ab34eb700c

test:
  secret_key_base: fdb4edcde14173d62963705ca4d7876b5307790924

production:
  secret_key_base: 85172605030a8225c083d886d066da2cb4aac1f0
Run Code Online (Sandbox Code Playgroud)

但我认为你不能像yml文件中的secret_token.rb那样运行ruby脚本.你如何让rails动态地秘密生成秘密令牌.该怎么做?什么是最佳做法?

tho*_*ler 1

您实际上可以在 YML 文件中运行 ERB 代码。就像是:

development:
  secret_key_base: <%= secret_token %>
Run Code Online (Sandbox Code Playgroud)

应该可以工作(如果读取 YML 文件的任何进程都可以访问 secure_token 方法)。