Building a simple token based authorization API with Rails.

Using Ruby on Rails and JWT+Knock to lockdown your application. Last updated Oct 23, 2017.

The first task I usually encounter when starting a new project is the user system, necessary but time-consuming. After I have finished creating the basic system and squashed all the noticeable bugs, that original motivation and drive I once had has disappeared. Only the desire for Netflix remains, for that reason alone, I wanted to build a simple and flexible authorization API. When setting up a new project, it would be as simple as cloning my authentication system and starting the server.

At the end of this tutorial, you will have a simple to use authorization system which can be easily integrated into an application giving you the ability to lockdown sections of your application.

This article is assuming you have a basic understanding of Ruby on Rails.

TL;DR/The code please:

Building the Application:

We will be using Knock as the foundation for our Authorization API. If you don’t want to read about it, below are a few sales points taken from their project page:

Light-weight

Tailored for Rails-API applications

Stateless

Step 1 — Project Setup:

Once you are ready to start, open up your terminal and enter the following commands below.

# This will create a new Rails API base.

# For this example we will use MySQL as the database.

rails new projectname --api -d mysql # Navigate to your new project

cd auth-api

Now that you have created your application and have navigated into the folder, open up your Gemfile. Make sure the following core gems are active and within the file.

# File location:

# - project_name/Gemfile gem 'bcrypt', '~> 3.1.7'

gem 'active_model_serializers'

gem 'rack-cors'

gem 'knock'

gem 'jwt'

It should look close to the Gemfile below:

Gemfile

Next up, run the following commands in your terminal. These will finish setting up your basic project structure.

bundle install # Run these commands to setup the basic Knock structure.

rails generate knock:install

rails generate knock:token_controller user # Next run the following commands to prepare your Rails application.

rails generate model users

rails generate controller users

rails generate controller home

rails g serializer user

rails db:create

Step 2 — Database Setup:

Now, we will be setting up the basic Users table for our application. Since we are only creating a basic system, we will keep the database structure simple.

Knock uses the email address field for verification purposes. We will use the role field for giving our application a simple permissions system.

Open up the following file below and add in the following code:

# File location:

# - project_name/db/migrate/:random_number_create_users.rb

Migration File

Enter the following command in your terminal to create your User table:

rails db:migrate

Step 3 — Authorization/Knock Setup:

First, we are going to configure Knock for our application. Knock makes this a very simple process where you only need to uncomment the settings you wish to use.

Make sure the following lines below are uncommented in your file:

# File Location:

# - project_name/config/initializers/knock.rb

Knock Settings

Next, we will need to setup our User model. We will be setting up some basic validations and methods for later use.

# File Location:

# - project_name/app/model/user.rb

User Model

Now, we will setup the all the controllers that are necessary for our Authentication API.

# File Location:

# - project_name/app/controller/application_controller.rb

Application Controller

# File Location:

# - project_name/app/controller/home_controller.rb

Home Controller

Step 4 — User Setup

Next up, we will create the methods for account creation and handling authentication. These are the base methods needed to start testing our API.

# File Location:

# - project_name/app/controller/users_controller.rb

Users Controller — Part one

We will now add some basic methods for user creation and management. This will give users access to create and update their accounts and give administrators the ability to delete users.

Users Controller — Part two

Lastly, we need to edit our User Serializer that we created at the start. We will be using the serializer to avoid sending sensitive data from our API.

# File Location:

# - project_name/app/serializers/user_serializer.rb

User Serializer

Step 5 — Finalize and Test

Since all the code has now been setup for our Authorization API, we need to add our API routes before we start testing.

We will be adding the end-points for all the methods we created.

# File Location:

# - project_name/config/routes.rb

Routes

Now that all our routes are present, it’s time to start the application on our local environment.

# Open Terminal and enter:

Rails s -p 5000

When testing our Authorization API, we will be using the application Postman. Postman is a free and simple tool to use for testing back-end API’s.

First, let’s start by testing our user creation route. We only need to set the body with our new account details.

Postman: User create

Next, let’s test our login route Knock has generated.

Postman: Login

If everything worked, we should’ve of received our JWT Token from Knock, which should look like my result below.

Postman: Login result

Now that we have our JWT token, lets try calling our authorized route with our generated token. To send our token to the API, we will need to add an Authorization key with the following format:

Bearer generated_key

Your Postman should look like my settings below:

Postman: Authorization key

Once you have added your Authorization key, click the send button. You should receive a “status: 200” and the message we set up in the Home Controller.

Postman: Authorized result

Next up, let’s make sure our authorization system is working properly. Start by un-checking the Authorization key we set before. Once it’s disabled, try sending the request again and see if you receive back a status code: 401 Unauthorized.

Postman: Unauthorized

Now we can use our Authorization API to authenticate front-end platforms or to authenticate other back-end API’s. How we can authorize our external systems using our API is a simple process, and below is the general idea behind it.

Front-end Example: We would call the route localhost/users/current with our generated JWT Token. If the token is valid we will receive that users information and if it’s not we will receive unauthorized.

Back-end Example: We would call the route localhost/users/current with our generated JWT Token. If the token is valid, we will receive that users information. Then we can then set the rails method current_user, otherwise we receive unauthorized.

Conclusion

Hopefully this article has given you a strong base on building a simple and flexible authentication system. Now you can get started building your new web application. If there is enough interest I would be happy to release a part two. Which will dive into email verification and building out a password reset system.

Git Repo:

If this article has been helpful in anyway, please click/hold the green clap button. If you are feeling very generous, feel free to share it to your inner circle so you can virtually brag about your newly learned knowledge.

Thanks for reading.