Keeping API Keys Secret in Ruby on Rails

Spoiler: Use Environment Variables!

Jeffrey Konowitch
WDI NYC Jan 2014
1 min readFeb 14, 2014

--

When writing web applications we often interact with 3rd party APIs using private authentication credentials. Instead of committing our private API keys to our codebase (insecure!) let’s learn how to make use of environment variables to keep our keys secret.

Environment variables are key/value pairs which are stored by your operating system, and can be accessed by any running program. To see a list of these, in your terminal type the `env` command.

You should see something like this:

$ envTERM_PROGRAM=Apple_TerminalSHELL=/bin/bashTERM=xterm-256colorHISTSIZE=32768CLICOLOR=1

Why is helpful. Well, we can add our private API keys as environment variables and then access them in our Rails application. That way, they never hit our code base!

  1. Add your API keys as environment variables. In your `~/.bash_profile`:
export INSTAGRAM_CLIENT_ID=”34SDKJ$ASDKJDS”

2. In the terminal:

source ~/.bash_profile

3. In your Rails app — create a `config/initializers/api.rb` file and add:

INSTAGRAM_CLIENT_ID = ENV[“INSTAGRAM_CLIENT_ID”]

Initializers are run when your Rails app boots up. What this line does is it creates a global constant `INSTAGRAM_CLIENT_ID` and assigns it to the value of the environment variable from your operating system with they same name. Because this is a global variable, you can now use it anywhere in your Rails app!

Epilogue

If you are deploying your app to Heroku, take a look at these instructions on how to set environment variables on your production server: https://devcenter.heroku.com/articles/config-vars

--

--

Jeffrey Konowitch
WDI NYC Jan 2014

I get giddy and excited when I learn new things. Engineer and Instructor at General Assembly (@GA), actor, director, and human.