How to Use Figaro for Easy OAuth on Heroku

If you’ve allowed users to log into your Rails app through Facebook (or Google, or Twitter, or…) you know the basics of OAuth. You know that you shouldn’t commit your Facebook application’s key and secret into your public Github repo. You might have used the fantastic dotenv or figaro gems to store your configuration variables in environment while in development.

Everything works great on localhost. So now what do you do when it’s time to deploy? Here’s what I did to keep my Facebook OAuth flow working in a production environment on Heroku.

Install Figaro

If you haven’t already been using Figaro while in development mode, made sure it’s installed now. Add gem 'figaro' to your Gemfile and run bundle install. Then run bundle exec figaro install. This will generate a config/application.yml file and automatically enter it into your .gitignore.

Get a Production Key and Secret

You don’t want to use the same application key and secret that you used for development – for one thing, you’re not on the localhost domain any more! Create a new app on Facebook (or Google, or…), and enter your Heroku web address as the app domain. Be sure to set up the OAuth redirect url with your Heroku url too.

Configure Figaro

Copy the brand-new application key and secret you just created for your production environment. Open up config/application.yml. Figaro supports grouping by environments, so create a new production group and save your key and secret:

  facebook_key: "your-facebook-key"
  facebook_secret: "your-facebook-secret"

Replace your-facebook-key and your-facebook-secret with your actual key and secret. You can define a facebook_key and facebook_secret outside of the production group – aka your development and test environment config data – and Figaro will use the correct data depending on your Rails environment.

Configure Omniauth

Open up the config file generated by the Omniauth gem, config/initializers/omniauth.rb. Now you can reference ENV[‘facebook_key’] and ENV[‘facebook_secret’], and Figaro will fill in the correct values based on your environment. It should look like this:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, ENV["facebook_key"], ENV["facebook_secret"]

Configure Heroku

Heroku has a built-in way to set up environment configuration, but Figaro makes it even easier. In your application directory – assuming you’ve already deployed to Heroku – just run this single Figaro command to set values from config/application.yml all at once: figaro heroku:set -e production.

Now you should be able to log in to your app smoothly!

Written on July 12, 2016