Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically generate secret tokens in Rails 4.1 with secrets.yml?

New to rails. Followed Hartl's tutorial where he uses this code to dynamically generate secret token for 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

I'm trying to follow the new Rails 4.1 way by using secrets.yml, and delete the secret_token.rb:

development:
  secret_key_base: 79c1389c2fadc5a5a1918a5104ab34eb700c

test:
  secret_key_base: fdb4edcde14173d62963705ca4d7876b5307790924

production:
  secret_key_base: 85172605030a8225c083d886d066da2cb4aac1f0

But I think you cannot run ruby script like the one in secret_token.rb in a yml file. How would you have rails dynamically generate the secret tokens in secret. How should this be done? What is best practice?

like image 947
Andreas Avatar asked Feb 10 '14 09:02

Andreas


2 Answers

Given a function secret_token whose only job is to generate a new token string each time one's application accesses the secrets.yml file, cookies and most likely other session-like behavior will not work correctly as the secret token changes each call to the function.

The preferred & secure way is to use any old secret key in the secrets.yml file for development and test environments (you can generate a secret string by issuing rake secret on the command line), then use an environment variable that your production server knows, so the secrets.yml file looks like:

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

For example, on Heroku, use heroku config:set SECRET_KEY_BASE="insert key here" to set the environment variable and there you have it. Don't be afraid to check the secrets.yml file into scm...as long as you haven't saved your production key to the file (and are instead using the environment variable method I just described), checking the file into scm poses no threat.

like image 128
Steve Nims Avatar answered Oct 14 '22 09:10

Steve Nims


You can actually run ERB code in YML files. Something like:

development:
  secret_key_base: <%= secret_token %>

should work (if whatever process reads the YML file can access the secure_token method).

like image 1
thorsten müller Avatar answered Oct 14 '22 08:10

thorsten müller