Securing secret token by generating new token dynamically

Many of us already know the reason to omit pushing secret token into version repository to secure the application.

Attacker can take the secret token and re-generate valid cookies for your applications or check out what other users have inside their account. The solution is to:

  • Generate manual key
  • Not push the token into version repository
  • Add token with environment variable
  • Dynamically generate a random secret key

I’m using a small code snippet below to generate a key dynamically:


require 'securerandom'

def find_secure_token
token_file = Rails.root.join('.secret_token')

if File.exist?(token_file)
File.read(token_file).chomp
else
token = SecureRandom.hex(64)
f = File.new(token_file, 'w')
f.write(token)
f.close
token
end
end

# Dynamically generate random security key
secret_key = find_secure_token
AppName::Application.config.secret_token = secret_key

Hope it will help!

Leave a Comment