Better Programming

Advice for programmers.

Follow publication

Member-only story

Build a Rails API With JWT

Reinald Reynoso
Better Programming
Published in
6 min readApr 2, 2020

Photo by Joshua Fuller (Unsplash)

This is a guide on creating and setting up a Rails API application from scratch.

The focus will be on user login and sign up and authorizing/authenticating them with JWT (JSON Web Tokens). Keep in mind that this approach represents one of many. Let’s begin with the setup.

Setup

Let’s generate a Rails API. From the terminal, run the following command:

rails new jwt-rails-api-app --database=postgresql --api

The flag --database=postgresql is included to indicate that PostgreSQL is to be utilized as the database instead of SQLite, and the flag --api is included to indicate that this application is to be set up as an API and to avoid generating the views and view helpers since they are not necessary for an API.

Open the newly generated folder and open Gemfile. We need to include a few gems as part of the setup.

The first is to uncomment/include:

gem 'bcrypt'

Bcrypt will manage hashing the passwords for the user.

The second is to uncomment/include:

gem 'rack-cors'

This allows the Cross-Origin Resource Sharing (CORS) in the API. CORS prevents API calls from unknown origins.

And finally, include:

gem 'jwt'

From the terminal, run bundle install to install the three gems in the application.

Next, navigate to config/initializers/cors.rb and uncomment the following and also replace “example.com” with an asterisk.

CORS

Now, navigate to config/routes.rb. We will define the routes accessible for this application.

For this guide, we will only focus on the routes that handle login, signing up a user, and auto-login. We will define a couple of custom routes to handle the login and auto-login.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Reinald Reynoso
Reinald Reynoso

Written by Reinald Reynoso

Full Stack Developer || Educator || Lifelong Learner

Responses (6)

Write a response