Rails 5 API + JWT Setup : Easy familiar way with Devise

Ashish Wadekar

To start off: This post is an imporvisation & is inspired by a similar post which tries to solve the same problem.

Rails 5 is the most agile way of converting your next idea into a reality. With the rush of all great JS frameworks & mobile application platforms, building an API only platform is definitely the way forward.

STEP 0 — Install Ruby & Rails on your machine

Follow this excellent post for getting started

STEP 1 — Creating a new Rails app in API mode

$ rails new my_api --api

STEP 2 — JWT Authentication with Devise & Devise-JWT

JWT Authentication is a secure way of managing authentication for API applications. You can learn more about JWT here. Authentication will be handled by one the most favourite and stable authentication solution in rails world — Devise . This forms the basis of authentication in our app. We don’t need to install Devise explicitly because we are going to use devise-jwt , an extension which uses JWT tokens for authentication. Let’s add the gem to our Gemfile

gem 'devise-jwt'

Install this gem in our application by running this command in your application location:

$ bundle install

Finish this installation by following the instructions provided here. We are creating the User model and running the devise installation scripts.

STEP 3 — Adding the JWT Revocation Strategy

JWT Revocation strategy is necessary for a secure environment. You can go through this article to learn more.

Now, we will create the JWT Blacklist table & then add the revocation strategy to refer this table for revocation.

Create a blank migration and add the following to that migration file

Now lets run this migration

$ rails db:migrate

We need to enhance the JwtBlacklist model we just created with Devise revocation strategy. Add details to the newly created model from details below:

It is time to add this revocation strategy to User model

This sets up our models and we can move to setup devise, routes & sessions controller.

STEP 4 — Exposing the login / logout functionality in Devise

We will proceed with adding login & logout endpoints to our setup. Modify the devise initializer by adding the following block to existing initializer. You will find this file here: config/initializers/devise.rb

Add Login / Logout endpoints to Devise

It is recommended to add a new secret generated with rails secret as jwt.secret as the exisiting devise secret maybe used by other components in application.

Last line in the configuration above will prevent raising flash messages which are unnecessary in this context & not present in Rails api mode.

config.navigational_formats = []

STEP 5 — Adding login / logout routes

We will now add the login / logout routes so that we can access earlier added functionality. Default devise functionality is sufficient and now we want the application to respond with a json response. We will achieve this by creating Sessions Controller & modifying the Application as shown below:

The routes can now be exposed. Add the following block to routes.rb

We can configure custom paths for our endpoints. If you are ok with default Devise paths ( users/sign_in &users/sign_out ) just remove path and path_names keys.

STEP 6— CORS! Dealing with CORS

When dealing with API, CORS needs to be dealt with too! Let’s finish this by tweaking the config/initializers/cors.rb

What is essentially being done here is that we are allowing requests from internet by mentioning ‘*’ in origins. I know this is dangerous but you can limit the access by mentioning IP / URL here when you have the necessary details.

STEP 7 — Getting users authenticated

As we are using devise for authentication, our favourite current_user is available to us. This means PROFIT!

It was a fun ride to get our beloved Rails ready for the future.

Enjoy!

Ashish Wadekar

Written by

Simple. Straight forward. Down to the earth. Believer : We already have more than we need.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade