JSON Web Token (JWT) authentication is a simple and secure method for managing user authentication in web applications.

This post will show you how to implement JWT authentication in a Ruby on Rails application particularly on a Windows machine, step by step, with a focus on beginners.

What is JWT Authentication?

JWT is a lightweight, URL-safe token used to transmit information securely between a client and a server.

It's a popular choice for modern web applications because it’s stateless (no session data needed) and scalable, which is especially useful for APIs.

Prerequisites

Make sure you have the following installed on your Windows system:

  • Ruby on Rails (You can install Rails using gem install rails)
  • Basic knowledge of Ruby and Rails
  • A text editor like Visual Studio Code
  • Postman (for testing API requests)

Step 1: Install Required Gems

First, you need to install the JWT gem. Open the terminal or command prompt and run the following:

bash
gem install jwt

After installing the gem, add it to your Gemfile:

ruby
gem 'jwt'

Then, run bundle install to ensure the gem is installed.

Step 2: Create Authentication Controller

Generate an authentication controller to handle the login process:

bash
rails generate controller Authentication

In authentication_controller.rb, add the following code to handle the login process and generate a JWT token:

ruby
class AuthenticationController < ApplicationController
  def login
    user = User.find_by(email: params[:email])

    if user && user.authenticate(params[:password])
      token = encode_token(user.id)
      render json: { token: token }, status: :ok
    else
      render json: { error: 'Invalid credentials' }, status: :unauthorized
    end
  end

  private

  def encode_token(user_id)
    JWT.encode({ user_id: user_id }, Rails.application.secret_key_base, 'HS256')
  end
end

Step 3: Protect Routes Using JWT

To protect routes and ensure that only authenticated users can access certain actions, you need to create a method to decode the JWT token.

In your application_controller.rb, add the following method to decode the token:

ruby
class ApplicationController < ActionController::API
  def current_user
    decoded_token = decode_token
    if decoded_token
      user_id = decoded_token[0]["user_id"]
      @current_user = User.find_by(id: user_id)
    end
  end

  def decode_token
    if request.headers['Authorization']
      token = request.headers['Authorization'].split(' ')[1]
      begin
        JWT.decode(token, Rails.application.secret_key_base, true, algorithm: 'HS256')
      rescue JWT::DecodeError
        nil
      end
    end
  end

  def authorized?
    render json: { error: 'Not authorized' }, status: :unauthorized unless current_user
  end
end

Read more:
How to Make API Calls in Ruby on Rails
Rails 8.0 Release Highlights

Step 4: Secure Routes

Now, let’s secure a route so that only authenticated users can access it. For example, we’ll protect a ProfileController action that shows the logged-in user's profile.

Add the following to your profile_controller.rb:

ruby
class ProfileController < ApplicationController
  before_action :authorized?

  def show
    render json: @current_user
  end
end

The before_action :authorized? ensures that only logged-in users with a valid JWT token can access the show action.

Step 5: Test JWT Authentication

You can now test your JWT authentication using Postman or any API testing tool:

  1. Login: Send a POST request to /login with the user's email and password. If valid, you'll get a JWT token in the response.
  2. Access Protected Routes: Use the token to access protected routes. Add the token as a Bearer token in the Authorization header of your requests.

Example:

bash
Authorization: Bearer <your_jwt_token>

Key Benefits of JWT Authentication

  • JWT is Stateless, No need to store session data on the server.
  • JWT tokens can be signed for extra security.
  • It is Scalable and perfect for APIs and larger web applications.

By following this post, you've learned how to set up JWT authentication in your Ruby on Rails application on a Windows machine.

Please let me know the feedback in comments below. Thanks


Comments(0)