Skip to content

Instantly share code, notes, and snippets.

@cjolly
Last active August 4, 2023 08:21
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save cjolly/6265302 to your computer and use it in GitHub Desktop.
Save cjolly/6265302 to your computer and use it in GitHub Desktop.
How to securely set rails secret key when you deploy to Heroku.

Stop Versioning Rails Secret Tokens

After reading Code Climate's Rails' Insecure Defaults I realized I was guilty of breaking rule 3. Versioned Secret Tokens. Here's how I fixed it.

Use dotenv in development and test environments:

# Gemfile
gem 'dotenv-rails', groups: [:development, :test]

Local development key for dotenv:

echo RAILS_SECRET_KEY_BASE=`rake secret` > .env

Secure rails initializer:

# config/initializers/secret_token.rb
YourApp::Application.config.secret_key_base = ENV['RAILS_SECRET_KEY_BASE']

Securely set key on heroku. Keep your key out of your shell history and buffer:

heroku config:set RAILS_SECRET_KEY_BASE=`rake secret` > /dev/null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment