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

铁路新手。 按照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 

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

 development: secret_key_base: 79c1389c2fadc5a5a1918a5104ab34eb700c test: secret_key_base: fdb4edcde14173d62963705ca4d7876b5307790924 production: secret_key_base: 85172605030a8225c083d886d066da2cb4aac1f0 

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

给定一个函数secret_token,其唯一的工作是每当一个应用程序访问secrets.yml文件时生成一个新的令牌字符串,cookie和其他类似会话的行为很可能无法正常工作,因为秘密令牌会更改每次调用该函数。

首选和安全的方法是使用secrets.yml文件中的任何旧密钥进行开发和测试环境(您可以通过在命令行上发出rake secret来生成秘密字符串),然后使用生产服务器知道的环境变量,所以secrets.yml文件看起来像:

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

例如,在Heroku上,使用heroku config:set SECRET_KEY_BASE="insert key here"来设置环境变量,并且您拥有它。 不要害怕将secrets.yml文件检入scm …只要你没有将生产密钥保存到文件中(而是使用我刚才描述的环境变量方法),将文件检入scm没有威胁。

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

 development: secret_key_base: <%= secret_token %> 

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