Deploying a Rails API on Heroku with JWT Authentication Keys

David Ryan Morphew
4 min readSep 27, 2021

--

Keys to Your Success

Photo by Jason D on Unsplash

For the run-of-the-mill Rails 6 API deployment steps, you can follow along with any number of Heroku deployment guides, or the official one by Heroku.

Here I want to show you how to set up an API key for an external API, and how to to use keys with Heroku if you employ JWT authentication.

As I’m sure you already know if you’re here, you don’t ever want to expose your API key or secret keys on GitHub, or anywhere! An exposed API key can cost you a lot if someone else gets a hold of it.

Photo by Jp Valery on Unsplash

Contents

I Review: Use .env in Development for an API key

II Preparing Secret Key Base for Deployment on Heroku

III Adding Your Keys to Heroku in Deployment

IV An Alternative Method

Review: Use .env in Development for an API key

A useful way to hide your keys while you’re developing your app is to use something like dotenv.

As explained in the documentation (link above):

  1. Add this line to the top of your application’s Gemfile:
gem 'dotenv-rails', groups: [:development, :test]

2. Also: As early as possible in your application bootstrap process, load dotenv:

require 'dotenv/load'# or
require 'dotenv'
Dotenv.load

3. Run:

bundle install

4. Make sure you create a file in the top of the directory of the project called .env.

touch .env

5. Also (VERY IMPORTANT) be sure to add .env to .gitignore to keep the file from being pushed to GitHub.

.gitignore   # Ignore bundler config.
/.bundle
.env
# Ignore all logfiles and tempfiles.
/log/*
/tmp/*
!/log/.keep
!/tmp/.keep

6. Now you’re ready to add your API_KEY to the .env file:

.env   API_KEY=arjyli8465sbr6su13dnt68s4rb13tn68sbra

Note that the value of the key is set without quotation marks.

7. Wherever you need to use your Api key, you wrap the key name in

ENV[“API_KEY”]

Take, for example, this url I used for the Nasa Api:

class Api < ApplicationRecord   https://api.nasa.gov/mars-photos/api/v1/rovers/photos?
{date_query}&api_key=#{ENV["API_KEY"]}"

Preparing Secret Key Base for Deployment on Heroku

We’re going to jump ahead now to getting your JWT authentication ready for deployment with Heroku

  1. Make sure you have a file called secrets.yml in your config/ folder. In that file, add this code:
secrets.ymlproduction:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

(You could also put your API key in there if you’d like, but it’s not necessary as you’ll see below.)

Photo by Sammy Williams on Unsplash

2. In your authentication methods that encode and decode your JSON Web-Tokens (JWTs), use Rails.application.secrets.secret_key_base wherever you need to pass in your secret key… the second argument for JWT.encode and JWT.decode.

Your encoding and decoding methods may look something like this:

def encode_token(payload)
JWT.encode(payload, Rails.application.secrets.secret_key_base)
end
def decoded_token
if request.headers['Authorization']
token = request.headers['Authorization'].split(' ')[1]
begin
JWT.decode(token, Rails.application.secrets.secret_key_base,
true, algorithm: 'HS256')
rescue JWT::DecodeError
nil
end
end
end

Adding Your Keys to Heroku in Deployment

Now, you’re going to need to give Heroku access to your keys.

Heroku Dashboard Method

This part is actually really easy too. Once you’ve got your application deployed, you can add your keys on the Heroku Dashboard by hitting the button “Reveal Config Vars” under “Settings.”

Once you’ve opened that up, add the key name, such as API_KEY on the left with the corresponding value you have saved in your .env file.

Generate A Secret Key for SECRET_KEY_BASE

For the SECRET_KEY_BASE, in your Rails app you can run:

rake secret

and then copy and paste the output as the value corresponding to SECRET_KEY_BASE in Config vars.

Heroku CLI Method

Alternatively, you can use the Heroku CLI in you app to set the keys and values.

Now you should be good to go!

A beautiful sunrise to mark a new day
Photo by Zac Durant on Unsplash

An Alternative Method

For another approach, check out this post, too.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

David Ryan Morphew
David Ryan Morphew

Written by David Ryan Morphew

I’m very excited to start a new career in Software Engineering. I love the languages, frameworks, and libraries I’ve already learned / worked with (Ruby, Rails,

No responses yet

Write a response