加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何使用secrets.yml在Rails 4.1中动态生成秘

发布时间:2020-12-17 04:17:05 所属栏目:百科 来源:网络整理
导读:铁路新手.按照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(to
铁路新手.按照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配置:设置SECRET_KEY_BASE =“在此处插入键”来设置环境变量,并且您拥有它.不要害怕将secrets.yml文件检入scm …只要你没有将生产密钥保存到文件中(而是使用我刚才描述的环境变量方法),将文件检入scm没有威胁.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读