Introduction
Have you ever thought about where is the best place to put your JWT secret key, API Key, or any secret data in your project?
The answer to this question is inside the .config/credentials.yml.enc
file.
Yes, this file is encrypted, so that's why we can push .config/credentials.yml.enc
file to the git repository.
Editing credentials.yml.enc
Run this code in the terminal
#VS Code
EDITOR="code --wait" rails credentials:edit
#Atom
EDITOR="atom --wait" rails credentials:edit
Your IDE will open a new document that looks like this
According to rubyonrails.org,
By default, the credentials file contains the application's
secret_key_base
. It can also be used to store other secrets such as access keys for external APIs.
We can put our other secrets, such as the JWT secret key and API key in here.
jwt:
secret_key: hello
api: api-key
# Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
secret_key_base: ca8bae95decfb752601c30aff9bbe5e7f22587341f8b132765f2fb92ddab9d52d0ebf07b9ef840acce5aeeed9ed513c8329bb8cafdd1de06494a0d69c5466ee7
Don't forget to close the file and it will automatically save. The terminal will show this message.
Using the credentials
We can call it in .rb
file using this code
Rails.application.credentials.jwt[:secret_key] # hello
Rails.application.credentials.api # api-key
For testing purposes, you can run it in the rails console
Deploying the master.key
to Heroku
master.key
is needed everywhere, and we should make sure that our team members also get this master.key
file. When we want to deploy to the server, we should put what is inside the master.key
to the environment variable.
According to rubyonrails.org,
Rails uses
config/master.key
or alternatively looks for the environment variableENV["RAILS_MASTER_KEY"]
to encrypt the credentials file.
Run this in the terminal
heroku config:set RAILS_MASTER_KEY=`cat config/master.key`
If Heroku send this error
, you should include your Heroku app name like this
heroku config:set RAILS_MASTER_KEY=`cat config/master.key` --app 'heroku app name'
Check this post to learn how to deploy your rails project.
How to Deploy Rails API to Heroku (ruby-2.6.1) (PostgreSQL)
Raynaldo Sutisna ・ Feb 21 '21
Keep your master.key
safe!
You can't lost and change your master.key
, or your credentials can't be opened.
However, you can create your new .config/credentials.yml.enc
and .config/master.key
again by running this command in your terminal.
rails credentials:edit
Conclucion
I was so happy after I found this way to save my credentials. This is really helpful for keep safe your credentials. I hope this blog will be helpful, and please leave your comments if you have any questions!
Top comments (2)
thank you very much.
yes, it's so convenient!