Creating a Rails API With Jason Web Token (JWT) Authentication
Techie September 2022
Introduction
Token based authentication is an alternative method to session-based authentication.
The server creates a web token (JWT), encodes, serializes and signs it with
its own secret key so that when it’s tampered with, the server will know and reject it.
Because the JWT created contains all the information about the user, it is sent to the browser,
and so the server does not need to store information about the user.
Let’s create a Rails API that authenticates users with JWT.
Prerequisites
postman (desktop version)
Create the Project
1 . Create a rails API only project.
2 . Add JSON Web Token (JWT) and bcrypt gem in Gemfile.
3 . Bundle up
4 . Create the database
5 . Create the user model
6 . Require securerandom for generating session keys.
7 . Generate users controller.
8 . Add actions in users controller.
9 . Create JsonWebToken concerns in app/controllers/concerns.
10 . Create authenticate_request method in app/controllers/application_controller.rb.
11 . Create authentication controller and add the login method.
12 . Update routes
Test the application via postman
1 . Create a user
Notice the response containing the created user data at the bottom.
2 . Login
Notice the response containing the authorization token at the bottom.