Using credentials in Rails 6

Here is the thing, a couple of days ago I was trying to configure devise gem on my Rails 6 application, this lead me to have some research about how can I add credentials in order to use it properly with the OmniAuth method that is also available through devise. This lead me to have a conversation with my mentor and asked how can I change my credentials since this was not working on production, but... it was working locally.

config/initializers/devise.rb :

 # ==> OmniAuth
 # Add a new OmniAuth provider. Check the wiki for more information on setting
 # up on your models and hooks.
 # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
  config.omniauth :google_oauth2,
                  Rails.application.credentials.dig(:google, :google_client_id),
                  Rails.application.credentials.dig(:google, :google_client_secret),
                  scope: ', userinfo.profile',
                  skip_jwt: true

So I had to change the scope of the credentials to also be reachable on deployment. This lead me to find out the new way Rails 6 handles the credentials.yml.enc file on your application.

Before, and as I learned from my mentor, with the command (Rails 5.1)

rails secrets:edit

was enough to get through the configuration, but after Rails 5.2 secrets was replaced with credentials.

How did I updated them now?

First I added a new credentials files to be handled in production. This is available in Rails 6! by doing:

$ rails credentials:edit --environment production

The above command does the following: (do not commit this files)

  • Creates config/credentials/production.key if missing.
  • Creates config/credentials/production.yml.enc if missing.
  • Decrypts and opens the production credentials file in the default editor.

Now we have a production.key available which WE WILL ONLY SHARE WITH OUR trusted team members.

Now we can add the credentials and save them:

  access_key_id: <your keys goes here>
  secret_access_key: <your keys goes here>

Save the changes and now we can check in our console with the command:

$ RAILS_ENV=production rails c
> Rails.application.credentials.config
#=> {:aws=>{:access_key_id=>"1f3649fe-ebbd-11e9-81b4-2a2ae2dbcce4", 
:secret_access_key=>"--your key will appear here"}}
#=> "--your key will appear here"

Finally I added for the Heroku deployment my production key:

# Setting master key on Heroku 
heroku config:set RAILS_MASTER_KEY=`cat config/credentials/production.key`

We can either use the generic environment variables RAILS_MASTER_KEY or an specific like RAILS_PRODUCTION_KEY.

No Comments Yet