The conventional way of API authentication is via a secret token. Though this serves the purpose, but JWT adds a lot of flexibility and information when want to communicate via tokens.

As per RFC7519:

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.

What is JWT:

A JWT consists of three components, which are joined with a dot(.).

aaaaaa.bbbbbb.cccccc

Header: Has two information, 1. Type of token, 2. Hashing algorithm Payload: Metadata Signature: Secret key

We’ll not dive too deep into JWT definition, as it’s beyond the scope of this article.

In this tutorial, we’ll walk through a way, using which we can implement secure API authentication using JWT.

Step 1: Add ‘jwt’ gem to Gemfile and do bundle install .

Step 2: let’s create an Auth module inside lib:

Step 3: Depending upon, whether we have a pure API application or we’re exposing an API from a Rails web app, we’ll need to place our authentication logic either in ApplicationController or the Main controller of API.

Step 4: Issue a authentication token:

A. Add “has_secure_password” to user.rb.

B. Add login route to “routes.rb”

namespace :api, path: '', defaults: {format: :json} do

constraints subdomain: 'api' do

scope module: :v1 do

post '/login' => 'sessions#create'

end

end

end

Now we’ve setup a “POST /login” url to issue a JWT, which can be further used by “authenticate” method in “main_controller.rb” to validate the authentication.

I enjoyed implementing it for my Rails API application. Though, all the steps should be self-explanatory, however I’ll be happy to help with any kind of issue you face while implementing authentication using JWT.