Create Task Manager app: Create Task CRUD supported by JWT authentication, Integrate Github Actions with Rspec tests

We maintain a simple rule: Controllers orchestrate HTTP. Services perform business operations. Models enforce domain and persistence rules. Blueprints control API representation.

This separation is enough for our current application and scales reasonably well without over-engineering. Our next step remains React application structure and API integration. We’ll leave the optional backend refactoring and additional model tests until later.

I will introduce one important architectural improvement: a separate authenticated API base controller. This keeps registration and login public while protecting all Task endpoints automatically.

Step 4.5 – JWT authentication and protected Task APIs

1. Create Api::V1::BaseController

Create:

mkdir -p app/controllers/api/v1

touch app/controllers/api/v1/base_controller.rb

Our controller hierarchy will be:

ApplicationController
       |
       β”œβ”€β”€ RegistrationsController
       |
       β”œβ”€β”€ SessionsController
       |
       └── Api::V1::BaseController
                  |
                  └── TasksController

Why this design?

  • Registration doesn’t require authentication.
  • Login doesn’t require authentication.
  • Task endpoints require authentication.
  • We don’t need to repeat authentication callbacks in every Task controller.

Rails API controllers support before_action callbacks.

Implement BaseController

backend/app/controllers/api/v1/base_controller.rb

class Api::V1::BaseController < ApplicationController
  before_action :authenticate_request!

  attr_reader :current_user

  rescue_from ActiveRecord::RecordNotFound, with: :render_not_found

  private

  def authenticate_request!
    authorization = request.headers["Authorization"].to_s

    match = authorization.match(/\ABearer\s+(\S+)\z/i)

    return render_unauthorized unless match

    payload = Authentication::TokenVerifier.verify(match[1])

    return render_unauthorized unless payload

    user_id = payload["sub"]

    unless user_id.is_a?(String) && user_id.match?(/\A[1-9]\d*\z/)
      return render_unauthorized
    end

    @current_user = User.find_by(id: user_id)

    render_unauthorized unless @current_user
  end

  def render_unauthorized
    render json: {
      errors: ["Unauthorized"]
    }, status: :unauthorized
  end

  def render_not_found
    render json: {
      errors: ["Resource not found"]
    }, status: :not_found
  end
end

Understand the authentication process

A. Extract the Bearer token authorization = request.headers["Authorization"]

React will send: Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...

We extract the token after Bearer.

B. Verify the JWT payload = Authentication::TokenVerifier.verify(token)

Our existing service verifies the signature, algorithm and claims.

C. Identify the User User.find_by(id: payload["sub"])

Why query the database? JWT verification proves the token was signed by our application. It doesn’t prove that the user still exists or hasn’t been deleted.

D. Expose current_user

We use: attr_reader :current_user

All child controllers can now access: current_user. This becomes the foundation for authorization.


Q) Our base controller has helper codes like regExp matching and extract Bearer from headers. How can we clean the code?

As our application grows, we should avoid turning controllers into large classes containing authentication, serialization, cookie management and business logic.

My recommendation is to use private controller methods for controller-specific operations, Controller Concerns for reusable controller behaviour, and Service Objects for business logic.

But don’t extract every private method into a separate file. That can make a small application unnecessarily complicated.

1. Where should controller helper methods go?

Let’s establish some conventions for our project.

ResponsibilityRecommended location
Request parameter filteringController private methods
HTTP response handlingController private methods
Authentication logicService objects
JWT generation and verificationapp/services/authentication/
Refresh-token managementapp/services/authentication/
Cookie managementController private methods or controller concern
Shared authentication callbacksapp/controllers/concerns/
JSON serializationapp/blueprints/
Model business rulesActiveRecord models
Shared API authenticationApi::V1::BaseController

Rails provides app/controllers/concerns specifically for reusable controller behaviour. Rails also recommends keeping helper methods that aren’t controller actions private.

Our recommended backend structure

backend/app/
β”‚
β”œβ”€β”€ blueprints/
β”‚   β”œβ”€β”€ user_blueprint.rb
β”‚   β”œβ”€β”€ session_blueprint.rb
β”‚   └── task_blueprint.rb
β”‚
β”œβ”€β”€ controllers/
β”‚   β”œβ”€β”€ application_controller.rb
β”‚   β”‚
β”‚   β”œβ”€β”€ api/
β”‚   β”‚   └── v1/
β”‚   β”‚       β”œβ”€β”€ base_controller.rb
β”‚   β”‚       β”œβ”€β”€ registrations_controller.rb
β”‚   β”‚       β”œβ”€β”€ sessions_controller.rb
β”‚   β”‚       └── tasks_controller.rb
β”‚   β”‚
β”‚   └── concerns/
β”‚       └── api/
β”‚           └── v1/
β”‚               └── refresh_cookie.rb  # Only when shared
β”‚
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ user.rb
β”‚   β”œβ”€β”€ task.rb
β”‚   └── refresh_session.rb
β”‚
└── services/
    └── authentication/
        β”œβ”€β”€ base.rb
        β”œβ”€β”€ error.rb
        β”œβ”€β”€ access_token.rb
        β”œβ”€β”€ token_verifier.rb
        └── refresh_token.rb

This is sufficient. We don’t need repositories, interactors or additional architectural layers.

2. What should we do with our existing SessionsController?

Let’s examine its methods.

Existing methodMy recommendation
login_paramsKeep private in SessionsController
render_sessionKeep private; it orchestrates an HTTP response
render_invalid_credentialsKeep private
set_refresh_cookieKeep private for now
clear_refresh_cookieKeep private for now
verify_frontend_origin!Keep private for now
authenticate_request!Move responsibility to BaseController
JWT generationAlready correctly extracted to AccessToken
JWT verificationAlready correctly extracted to TokenVerifier
Refresh-token operationsAlready correctly extracted to RefreshToken

Why not move everything into concerns?

A concern is useful when multiple controllers share meaningful behaviour.

For example, if both SessionsController and another controller need the same cookie management:

app/
└── controllers/
    └── concerns/
        └── api/
            └── v1/
                └── refresh_cookie.rb

But currently SessionsController owns those operations. Extracting them now doesn’t provide much benefit.

Also, don’t move cookie-setting methods into app/helpers. Rails helpers are primarily intended for view presentation, not HTTP cookie management or business logic.

2. Create TaskBlueprint

Create: touch app/blueprints/task_blueprint.rb

backend/app/blueprints/task_blueprint.rb:

class TaskBlueprint < Blueprinter::Base
  identifier :id

  fields :title, :description, :status, :created_at, :updated_at
end

We deliberately exclude user_id from the normal frontend representation. The frontend doesn’t need to decide ownership.

3. Create TasksController

Create: touch app/controllers/api/v1/tasks_controller.rb

Implement the CRUD actions.

class Api::V1::TasksController < Api::V1::BaseController
  before_action :set_task, only: %i[show update destroy]

  def index
    tasks = current_user.tasks.order(created_at: :desc)

    render json: TaskBlueprint.render_as_hash(
      tasks,
      root: :data
    ), status: :ok
  end

  def show
    render_task
  end

  def create
    task = current_user.tasks.new(task_params)

    if task.save
      render json: TaskBlueprint.render_as_hash(
        task,
        root: :data
      ), status: :created
    else
      render_validation_errors(task)
    end
  end

  def update
    if @task.update(task_params)
      render_task
    else
      render_validation_errors(@task)
    end
  end

  def destroy
    @task.destroy!
    head :no_content
  end

  private

  def set_task
    @task = current_user.tasks.find(params[:id])
  end

  def task_params
    params.require(:task).permit(:title, :description, :status)
  end

  def render_task
    render json: TaskBlueprint.render_as_hash(
      @task,
      root: :data
    ), status: :ok
  end

  def render_validation_errors(task)
    render json: {
      errors: task.errors.full_messages
    }, status: :unprocessable_entity
  end
end

4. Important Rails security lesson

Look closely at this line: @task = current_user.tasks.find(params[:id])

This is one of the most important lines in our application.

Consider:

User A -> Task 10
User B -> Task 20

User A sends: GET /api/v1/tasks/20

If we write: Task.find(params[:id])

User A can retrieve User B’s task. This is an IDOR (Insecure Direct Object Reference) / broken object-level authorization vulnerability.

Instead: current_user.tasks.find(params[:id])

Rails searches only within the authenticated user’s tasks.

If User A requests Task 20, Rails raises ActiveRecord::RecordNotFound and our controller returns 404 Not Found. Notice that strong parameters alone cannot prevent this vulnerability. We need ownership checks at the query level.

5. Configure Task routes

Update config/routes.rb:

namespace :api do
  namespace :v1 do
    post "auth/register", to: "registrations#create"

    post "auth/login", to: "sessions#create"
    post "auth/refresh", to: "sessions#refresh"
    delete "auth/logout", to: "sessions#destroy"

    resources :tasks, only: %i[index show create update destroy]
  end
end

Check:

rails routes -g tasks                   
      Prefix Verb   URI Pattern                 Controller#Action
api_v1_tasks GET    /api/v1/tasks(.:format)     api/v1/tasks#index
             POST   /api/v1/tasks(.:format)     api/v1/tasks#create
 api_v1_task GET    /api/v1/tasks/:id(.:format) api/v1/tasks#show
             PATCH  /api/v1/tasks/:id(.:format) api/v1/tasks#update
             PUT    /api/v1/tasks/:id(.:format) api/v1/tasks#update
             DELETE /api/v1/tasks/:id(.:format) api/v1/tasks#destroy

Expected routes:

MethodEndpointAction
GET/api/v1/tasksindex
GET/api/v1/tasks/:idshow
POST/api/v1/taskscreate
PATCH/api/v1/tasks/:idupdate
DELETE/api/v1/tasks/:iddestroy

6. Task API request specs

Here are the essential request specs.

Create: touch spec/requests/api/v1/tasks_spec.rb

backend/spec/requests/api/v1/tasks_spec.rb:

require "rails_helper"

RSpec.describe "API V1 Tasks", type: :request do
  let(:user) { create(:user) }
  let(:token) { Authentication::AccessToken.issue(user) }

  let(:headers) do
    { "Authorization" => "Bearer #{token}" }
  end

  let(:endpoint) { "/api/v1/tasks" }

  describe "GET /api/v1/tasks" do
    it "returns only the authenticated user's tasks" do
      tasks = create_list(:task, 2, user: user)
      create(:task) # Another user's task

      get endpoint, headers: headers

      expect(response).to have_http_status(:ok)

      ids = response.parsed_body["data"].pluck("id")

      expect(ids).to match_array(tasks.pluck(:id))
    end

    it "rejects requests without a JWT" do
      get endpoint

      expect(response).to have_http_status(:unauthorized)
    end

    it "rejects invalid JWT" do
      get endpoint, headers: {
        "Authorization" => "Bearer invalid-token"
      }

      expect(response).to have_http_status(:unauthorized)
    end
  end

  describe "GET /api/v1/tasks/:id" do
    it "returns an owned task" do
      task = create(:task, user: user)

      get "#{endpoint}/#{task.id}", headers: headers

      expect(response).to have_http_status(:ok)
      expect(response.parsed_body.dig("data", "id")).to eq(task.id)
    end

    it "does not expose another user's task" do
      another_user_task = create(:task)

      get "#{endpoint}/#{another_user_task.id}", headers: headers

      expect(response).to have_http_status(:not_found)
    end
  end

  describe "POST /api/v1/tasks" do
    let(:task_params) do
      {
        task: {
          title: "Learn React",
          description: "Understand React hooks",
          status: "pending"
        }
      }
    end

    it "creates a task for the authenticated user" do
      expect {
        post endpoint, params: task_params, headers: headers
      }.to change(Task, :count).by(1)

      expect(response).to have_http_status(:created)

      task = Task.find(response.parsed_body.dig("data", "id"))

      expect(task.user_id).to eq(user.id)
    end

    it "does not allow assigning another user through user_id" do
      another_user = create(:user)

      params = task_params.deep_merge(
        task: { user_id: another_user.id }
      )

      post endpoint, params: params, headers: headers

      created_task = Task.find(response.parsed_body.dig("data", "id"))

      expect(created_task.user_id).to eq(user.id)
    end

    it "returns validation errors for invalid task" do
      params = {
        task: { title: nil }
      }

      post endpoint, params: params, headers: headers

      expect(response).to have_http_status(:unprocessable_entity)
      expect(response.parsed_body["errors"]).to be_present
    end
  end

  describe "PATCH /api/v1/tasks/:id" do
    it "updates an owned task" do
      task = create(:task, user: user)

      patch "#{endpoint}/#{task.id}",
            params: { task: { title: "Updated task" } },
            headers: headers

      expect(response).to have_http_status(:ok)
      expect(task.reload.title).to eq("Updated task")
    end

    it "cannot update another user's task" do
      task = create(:task)

      patch "#{endpoint}/#{task.id}",
            params: { task: { title: "Hacked" } },
            headers: headers

      expect(response).to have_http_status(:not_found)
      expect(task.reload.title).not_to eq("Hacked")
    end
  end

  describe "DELETE /api/v1/tasks/:id" do
    it "deletes an owned task" do
      task = create(:task, user: user)

      expect {
        delete "#{endpoint}/#{task.id}", headers: headers
      }.to change(Task, :count).by(-1)

      expect(response).to have_http_status(:no_content)
    end

    it "cannot delete another user's task" do
      task = create(:task)

      expect {
        delete "#{endpoint}/#{task.id}", headers: headers
      }.not_to change(Task, :count)

      expect(response).to have_http_status(:not_found)
    end
  end
end

One detail: create(:task) automatically creates a different user because of our Task factory association. This is useful for testing cross-user access.

7. Run backend tests

bin/rails db:migrate
bin/rails db:test:prepare

Run: bundle exec rspec spec/requests/api/v1/tasks_spec.rb

Then: bundle exec rspec

8. Our backend is now ready for React

Backend milestone

Our API endpoints

MethodEndpointAuthentication
POST/api/v1/auth/registerPublic
POST/api/v1/auth/loginPublic
POST/api/v1/auth/refreshRefresh cookie
DELETE/api/v1/auth/logoutRefresh cookie
GET/api/v1/tasksJWT
GET/api/v1/tasks/:idJWT
POST/api/v1/tasksJWT
PATCH/api/v1/tasks/:idJWT
DELETE/api/v1/tasks/:idJWT

There is one remaining production consideration: access JWTs remain valid for their ten-minute lifetime even after refresh-session logout or revocation. Our current design accepts this bounded revocation delay. Immediate revocation would require additional server-side checks.

Next: React application

We’ll now start frontend development.

Our first milestones will be:

  1. Inspect Vite’s generated structure and understand main.tsx and App.tsx.
  2. Install Fluent UI React v9.
  3. Create the Task Manager two-panel layout.
  4. Set up TypeScript API types and an API client.
  5. Build Login and Registration forms.
  6. Implement JWT storage in React memory and refresh handling.
  7. Build the task list and selected-task details.
  8. Introduce hooks, TanStack Query and Redux Toolkit as needed.
  9. Cover React loading performance, lazy loading and code splitting.

I recommend starting GitHub Actions now, before React. Because we already have a Rails backend with RSpec tests, PostgreSQL, JWT services and request specs. This is the ideal point to introduce CI.

I would follow this order:

  1. Now: GitHub Actions – automate backend RSpec tests.
  2. Next: React development.
  3. After React: Extend GitHub Actions to run frontend linting, TypeScript checks, tests and production builds.
  4. Later: Docker and Docker Compose, followed by Docker image build verification in CI.
  5. CD: Leave deployment automation out of scope, as planned.

This also teaches you an important engineering practice: CI should evolve alongside the application, rather than being added only after development is complete.

Step 1 – Understand GitHub Actions

What is GitHub Actions?

GitHub Actions is a CI/CD automation platform integrated into GitHub. For our project, we’ll initially use only CI (Continuous Integration).

Imagine this workflow:

We push code. GitHub automatically creates a temporary environment, installs the dependencies, starts PostgreSQL and runs your tests.

We don’t need your MacBook to be running for this.

Understand the terminology

Before writing YAML, understand these concepts.

TermMeaningOur example
WorkflowComplete automation definitionBackend CI
Event / TriggerWhat starts a workflowpush
JobA group of related stepsRSpec job
RunnerMachine executing a jobubuntu-latest
StepIndividual operationInstall Ruby
ActionReusable automation componentactions/checkout
ServiceContainer dependency for a jobPostgreSQL
ArtifactFile produced by a workflowTest reports
SecretSensitive configurationDeployment credentials

These concepts will be reused when we introduce Docker and frontend CI.

Where do we create workflow files?

Remember our repository structure:

rails-react-task-manager/
β”‚
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ config/
β”‚   β”œβ”€β”€ spec/
β”‚   β”œβ”€β”€ Gemfile
β”‚   └── Gemfile.lock
β”‚
β”œβ”€β”€ frontend/
β”‚
└── .github/
    └── workflows/
        └── backend-ci.yml

Important GitHub discovers workflow files from the repository root’s .github/workflows/ directory, not backend/.github/workflows/.

Create the directory:

mkdir -p .github/workflows

touch .github/workflows/backend-ci.yml

Step 2 – Configure our first Backend CI workflow

We’ll create a workflow that runs RSpec whenever backend code is pushed or a pull request targets main.

One small change to JWT configuration

Remember our JWT signing secret is currently loaded from Rails credentials. Our GitHub runner won’t have your local config/master.key.

We should not copy your production Rails master key into GitHub Actions just to run tests.

In Authentication::Base, update the secret lookup:

secret = ENV["JWT_SECRET_KEY"].presence ||
         Rails.application.credentials.dig(:jwt, :secret_key)

This gives us two options:

  • CI and production can provide a secret through the environment.
  • Local development can continue using Rails encrypted credentials.

Also update the secret helper in your JWT specs to use the same lookup:

let(:secret) do
  ENV["JWT_SECRET_KEY"].presence ||
    Rails.application.credentials.dig(:jwt, :secret_key)
end

We’ll provide a disposable test-only key inside the workflow. It is deliberately not a production secret.

CI: Add PostgreSQL configuration in database.yml

Rails doesn’t necessarily include username, password, host and port explicitly in the generated PostgreSQL configuration. Rails can use PostgreSQL’s default connection settings, environment variables or a DATABASE_URL.

For our project, I recommend explicitly configuring the connection values using environment variables.

Open: backend/config/database.yml

Use:


# Shared PostgreSQL configuration
default: &default
  adapter: postgresql
  encoding: unicode

  host: <%= ENV.fetch("PGHOST", "127.0.0.1") %>
  port: <%= ENV.fetch("PGPORT", 5432) %>

  username: <%= ENV.fetch("PGUSER", ENV.fetch("USER", "postgres")) %>
  password: <%= ENV["PGPASSWORD"] %>

  # Maximum ActiveRecord connections per process
  max_connections: <%= ENV.fetch("RAILS_MAX_THREADS", 5) %>

development:
  <<: *default
  database: backend_development

test:
  <<: *default
  database: backend_test

production:
  <<: *default
  url: <%= ENV["DATABASE_URL"] %>

Where do these values come from?

Local development

For your MacBook:

PGHOST=127.0.0.1
PGPORT=5432
PGUSER=<your-postgresql-role>
PGPASSWORD=<your-password-if-configured>

You can identify your actual PostgreSQL role by running:

psql -h 127.0.0.1 -p 5432 -d postgres -c "SELECT current_user;"

The USER fallback assumes your PostgreSQL role matches your macOS username. Override PGUSER when that isn’t true.

GitHub Actions

Our existing workflow already defines:

env:
  PGHOST: 127.0.0.1
  PGPORT: 5432
  PGUSER: postgres
  PGPASSWORD: postgres

These values will be picked up automatically by database.yml.

Notice that:

test:
  <<: *default
  database: backend_test

matches the PostgreSQL service database configured in our workflow.


I recommend starting GitHub Actions now, before React. Your reasoning is correct.

We already have a Rails backend with RSpec tests, PostgreSQL, JWT services and request specs. This is the ideal point to introduce CI.

I would follow this order:

  1. Now: GitHub Actions – automate backend RSpec tests.
  2. Next: React development.
  3. After React: Extend GitHub Actions to run frontend linting, TypeScript checks, tests and production builds.
  4. Later: Docker and Docker Compose, followed by Docker image build verification in CI.
  5. CD: Leave deployment automation out of scope, as planned.

This also teaches you an important engineering practice: CI should evolve alongside the application, rather than being added only after development is complete.

2. Write the workflow

Open: .github/workflows/backend-ci.yml

Add:


name: Backend CI

# When should GitHub execute this workflow?
on:
  push:
    paths:
      - "backend/**"
      - ".github/workflows/backend-ci.yml"

  pull_request:
    branches:
      - main
    paths:
      - "backend/**"
      - ".github/workflows/backend-ci.yml"

  #workflow_dispatch:

# Minimum permissions required by this workflow.
permissions:
  contents: read

# Cancel older runs when new commits arrive on the same branch.
concurrency:
  group: backend-ci-${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  rspec:
    name: RSpec - Ruby 4.0.9 / PostgreSQL 18
    runs-on: ubuntu-latest

    # PostgreSQL runs as a service container.
    services:
      postgres:
        image: postgres:18

        env:
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: backend_test

        ports:
          - 5432:5432

        options: >-
          --health-cmd "pg_isready -U postgres -d backend_test"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    # Environment variables available to all job steps.
    env:
      RAILS_ENV: test

      PGHOST: 127.0.0.1
      PGPORT: 5432
      PGUSER: postgres
      PGPASSWORD: postgres

      # Test-only JWT secret. Never reuse in production.
      JWT_SECRET_KEY: ci-only-jwt-signing-secret-do-not-use-in-production

    # Commands run from the backend directory.
    defaults:
      run:
        working-directory: backend

    steps:
      # Step 1: Download repository code.
      - name: Checkout repository
        uses: actions/checkout@v6

      # Step 2: Install Ruby and dependencies.
      - name: Setup Ruby
        uses: ruby/setup-ruby@v1
        with:
          ruby-version: "4.0.9"
          bundler-cache: true
          working-directory: backend

      # Step 3: Create and migrate test database.
      - name: Prepare test database
        run: bin/rails db:prepare

      # Step 4: Execute RSpec suite.
      - name: Run RSpec
        run: bundle exec rspec

This follows GitHub’s current Ruby CI guidance, including actions/checkout@v6 and ruby/setup-ruby@v1. The Ruby setup action supports Ruby 4.0.9 and automatically caches Bundler dependencies when bundler-cache: true is enabled.

Before running it, check backend/config/database.yml: its test configuration should use backend_test and allow the PGHOST, PGUSER, PGPASSWORD and PGPORT environment variables to control the PostgreSQL connection. The service container is configured with those credentials.

3. Understand every section

Let’s break down the important configuration.

A. on – workflow triggers

on:
  push:
  pull_request:
  workflow_dispatch:

These represent three different ways of starting the workflow.

TriggerWhat happens
pushRuns when you push backend code
pull_requestRuns when you create or update a PR targeting main
workflow_dispatchAllows you to manually run the workflow

We also added path filters.

paths:
  - "backend/**"

This means changes to the backend trigger backend CI. Later, frontend-only changes can run their own workflow without unnecessarily running Rails tests.

B. jobs – independent tasks

jobs:
  rspec:

A workflow can contain multiple jobs. For example, our future workflow architecture could have:

Backend CI
β”œβ”€β”€ RSpec
β”œβ”€β”€ RuboCop
└── Security checks

Frontend CI
β”œβ”€β”€ Oxlint
β”œβ”€β”€ TypeScript
β”œβ”€β”€ Vitest
└── Production build

Each job runs independently unless we explicitly configure dependencies between jobs.

C. runs-on – runner

runs-on: ubuntu-latest

This means GitHub will provide an Ubuntu virtual machine to run our job. Other options include:

  • Windows
  • macOS
  • Self-hosted runners

We’ll start with Ubuntu because it’s suitable for our Rails and PostgreSQL environment.

D. services – PostgreSQL

services:
  postgres:
    image: postgres:18

This starts PostgreSQL in a Docker container.


GitHub Actions Runner
       |
       β”œβ”€β”€ Ruby 4.0.9
       β”œβ”€β”€ Rails 8.1
       β”œβ”€β”€ RSpec
       |
       └── PostgreSQL Service
                  |
                  └── Port 5432

Understand this line:

ports:
  - 5432:5432

This maps the PostgreSQL container’s port 5432 to port 5432 on the runner.

The health-cmd makes GitHub wait until PostgreSQL is ready before executing subsequent steps. We’re learning container networking here, which will become useful when we configure Docker Compose.

E. actions/checkout

uses: actions/checkout@v6

Downloads your repository source code into the runner’s working directory. Without this, your runner wouldn’t have access to your Rails application files.

F. ruby/setup-ruby

- uses: ruby/setup-ruby@v1
  with:
    ruby-version: "4.0.9"
    bundler-cache: true

This action:

  1. Installs the specified Ruby version.
  2. Sets up Bundler.
  3. Installs gems from Gemfile.lock.
  4. Caches installed gems for subsequent workflow runs.

We don’t need a separate bundle install step.

G. Database preparation

- name: Prepare test database
  run: bin/rails db:prepare

This creates the test database if it doesn’t exist and applies pending migrations. We use RAILS_ENV: test because we want to prepare the test database.

H. Run RSpec

- name: Run RSpec
  run: bundle exec rspec

This executes our complete RSpec suite. If a test fails, this step fails and GitHub marks the workflow as failed.

Step 3 – Push and observe the workflow

From your repository root:

git status

git add .

git commit -m "ci: add backend rspec workflow"

git push

Now open GitHub repository.

Navigate to: GitHub repository β†’ Actions β†’ Backend CI

We can see our workflow executing.

Expected result: – All four stages should pass.

  1. Checkout repository.
  2. Setup Ruby.
  3. Prepare test database.
  4. Run RSpec.

We can click the RSpec job to see each step’s logs.

Step 4 – Understand what happens when a test fails

Backend CI failed

JWT::SignatureError:
       No verification key available
     # ./spec/services/authentication/token_verifier_spec.rb:10:in 'block (2 levels) in <main>'
     # ./spec/services/authentication/token_verifier_spec.rb:52:in 'block (4 levels) in <main>'

We have a warning too.

/home/runner/work/rails-react-task-manager/rails-react-task-manager/backend/vendor/bundle/ruby/4.0.0/gems/rspec-rails-8.1.0/lib/rspec/rails/matchers/have_http_status.rb:219: warning: Status code :unprocessable_entity is deprecated and will be removed in a future version of Rack. Please use :unprocessable_content instead.

Now we have something failed in CI. Let us see what’s the problem and fix it. and push again. The next workflow should pass. This is the fundamental CI feedback loop.

Issue Fixed: We missed ENV variable checks in token verifier spec file.

require "rails_helper"

RSpec.describe Authentication::TokenVerifier do
  let(:user) { create(:user) }
  let(:secret) { ENV["JWT_SECRET_KEY"].presence || Rails.application.credentials.dig(:jwt, :secret_key) }

Git Push again and check the Actions.

Step 5 – A few production practices to remember

The initial workflow is deliberately small. We’ll improve it incrementally.

1. Protect the main branch

Once the workflow is successful, configure GitHub branch protection or a ruleset to require the Backend CI status check before merging pull requests.

2. Pin GitHub Actions versions

We’re using version tags for this first learning exercise.

For production repositories, GitHub recommends pinning third-party actions to verified, full-length commit SHAs to protect against mutable-tag supply-chain attacks. Dependabot can help maintain those versions.

3. Keep permissions minimal

We have:

permissions:
   contents: read

Our tests don’t need permission to push commits, modify pull requests or publish packages.

Once Backend CI is green, we’ll start React development immediately. We’ll add the frontend CI workflow once the React application has its first working components. This way, we learn GitHub Actions using the actual application rather than separate artificial examples.

Create Task Manager app: Implement – Registration and Login APIs, Setup JSON Serializer

Let’s move to actual authentication APIs. We’ll implement Registration first, then Login. Keeping them separate will make it easier to understand password verification, JWT issuance and refresh-token management.

Step 4.3.1 – User Registration API

Our first endpoint, First authentication endpoint POST /api/v1/auth/register

1. Understand the registration flow

For this step, registration will create the User but won’t issue a JWT.

Why? We’ll implement login separately. Registration and authentication are different operations, even though some applications combine them.

2. Create the controller

Create these directories and file:

mkdir -p app/controllers/api/v1

touch app/controllers/api/v1/registrations_controller.rb

Controller: Api::V1::RegistrationsController

It should inherit from ApplicationController.

Implement one action: create

What should the action do?

A. Accept only permitted parameters

We should allow: email
password
password_confirmation

Never permit: password_digest
admin
role
account_status

The user must not be able to assign protected attributes through registration. Rails API applications include strong parameters and controller callbacks such as before_action through ActionController::API.

B. Create the user – Use the User model and handle validation failures.

C. Successful response – Return HTTP 201 Created.

Response contract:

{
  "user": {
    "id": 1,
    "email": "user@example.com"
  }
}

Important: Explicitly serialize only the allowed attributes. Don’t return user.as_json indiscriminately, because that could expose password_digest.

D. Failed response

Return HTTP 422 Unprocessable Entity.

Example:

{
  "errors": [
    "Email has already been taken"
  ]
}

Use the model’s validation errors rather than constructing your own validation logic in the controller.

3. Configure the API route

Open: backend/config/routes.rb

Add: POST /api/v1/auth/register

It should route to: Api::V1::RegistrationsController#create

Verify it: bin/rails routes

4. Write RSpec request specs

Create:

mkdir -p spec/requests/api/v1

touch spec/requests/api/v1/registrations_spec.rb

Use this structure:

RSpec.describe "API V1 Registration", type: :request do
  describe "POST /api/v1/auth/register" do
    # Examples
  end
end

Implement these five scenarios:

ScenarioExpected result
Valid registration201 Created
Duplicate email422 Unprocessable Entity
Missing email422 Unprocessable Entity
Missing password422 Unprocessable Entity
Malicious mass-assignment attributesProtected attributes ignored

Important security test

Imagine someone sends:

{
  "user": {
    "email": "attacker@example.com",
    "password": "password@1",
    "password_confirmation": "password@1",
    "password_digest": "attacker-controlled-value"
  }
}

Your controller must not permit password_digest. Verify that Rails generates the actual bcrypt digest from the submitted password instead. Also verify that the response does not contain password_digest. This is precisely the type of issue you might encounter in a Rails API controller security-review int.

5. Rate limiting – we’ll introduce it with Login

We’ll add rate limiting to the login endpoint because preventing password brute-force attempts is especially important.

Rails 8.1 provides:

rate_limit to: 10, within: 3.minutes, only: :create

By default, Rails scopes this limit by client IP and uses an ActiveSupport cache store. Exceeding the limit produces HTTP 429. We’ll also cover custom JSON responses for rate-limit failures.

6. Run and verify

Start Rails: bin/rails server -p 3000

You can manually test using curl:

curl -i -X POST http://localhost:3000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "user": {
      "email": "test@example.com",
      "password": "password@1",
      "password_confirmation": "password@1"
    }
  }'

Run RSpec:

bundle exec rspec spec/requests/api/v1/registrations_spec.rb

Step 4.3.2 – Login API

We’ll implement: POST /api/v1/auth/login

We’ll cover has_secure_password, authenticate, login rate limiting, refresh-token generation and cookie security.

Introducing JSON serializer: Blueprinter

I recommend using Blueprinter for our Rails API. It fits our application well, and I would introduce it now rather than building custom JSON serialization throughout our controllers.

We’ll also fix your registration implementation and request specs.

Blueprinter is a declarative JSON serialization library. It converts Ruby objects and ActiveRecord records into controlled JSON representations.
Github: https://github.com/procore-oss/blueprinter
Documentation: https://www.rubydoc.info/gems/blueprinter

Its main features are:

FeatureBenefit
Explicit fieldsControl exactly what the API exposes
ViewsDifferent response representations for different use cases
AssociationsSerialize related objects
Conditional fieldsInclude fields based on conditions
RenamingCustomize JSON attribute names
Collection renderingSerialize arrays and ActiveRecord relations

It also provides render_as_hash, which is useful when integrating with Rails controllers.

Is it actually fast?

Blueprinter is designed for performance, but I wouldn’t claim it is universally the fastest serializer.

For context, an older Rails 6.1/Ruby 2.7 benchmark found Blueprinter competitive with Alba and Panko, but the results depend on the workload and environment.

Three reasons to retaining Blueprinter for our project:

  1. Strong adoption relative to the alternatives.
  2. Explicit field definitions, views and association support.
  3. Enough flexibility for our User and Task API responses without introducing unnecessary complexity.

For our custom REST API, Blueprinter offers a good balance of readability, performance and maintainability.

Install Blueprinter

In backend/Gemfile, add: gem "blueprinter", "~> 1.3"

Then: cd backend
bundle install

The current RubyGems release listed is 1.3.0, and its declared minimum Ruby version is 3.1, so it meets our project’s declared Ruby requirement.

Create UserBlueprint

Create the directory and file:

mkdir -p app/blueprints

touch app/blueprints/user_blueprint.rb

Add:

class UserBlueprint < Blueprinter::Base
  identifier :id

  fields :email
end

Why only id and email?

Our User database record contains sensitive attributes. For example:

User
β”œβ”€β”€ id
β”œβ”€β”€ email
β”œβ”€β”€ password_digest
β”œβ”€β”€ created_at
└── updated_at

We only want:

{
  "id": 1,
  "email": "test@example.com"
}

This is an important security practice: explicitly whitelist fields for API serialization. Never serialize the entire ActiveRecord object. Blueprinter’s identifier and fields declarations give us control over exactly what is returned.

backend/app/controllers/api/v1/registrations_controller.rb:

class Api::V1::RegistrationsController < ApplicationController
  rate_limit to: 10, within: 3.minutes, only: :create

  def create
    user = User.new(registration_params)

    if user.save
      render json: UserBlueprint.render_as_hash(user, root: :data), status: :created
    else
      render json: { errors: user.errors.full_messages }, status: :unprocessable_entity
    end
  end

  private

  def registration_params
    params.require(:user).permit(:email, :password, :password_confirmation)
  end
end

Understand render_as_hash

Blueprinter offers different rendering methods:

MethodReturns
renderJSON string
render_as_hashRuby Hash
render_as_jsonJSONified Ruby Hash

We use: UserBlueprint.render_as_hash(user, root: :data)

This returns a Ruby Hash:

{
  data: {
    id: 1,
    email: "test@example.com"
  }
}

Rails then handles JSON encoding through: render json: ..., status: :created

One subtle but important point: avoid passing the JSON string returned by UserBlueprint.render into render json:. Rails could encode that string as another JSON string. render_as_hash avoids that issue.

Our API response contract

Successful registration – 201 Created

{
  "data": {
    "id": 1,
    "email": "test@example.com"
  }
}

Failed registration – 422 Unprocessable Entity

{
  "errors": [
    "Email has already been taken"
  ]
}

backend/spec/requests/api/v1/registrations_spec.rb:

require "rails_helper"

RSpec.describe "API V1 Registration", type: :request do
  let(:endpoint) { "/api/v1/auth/register" }

  let(:valid_params) do
    {
      user: {
        email: "test@example.com",
        password: "password@1",
        password_confirmation: "password@1"
      }
    }
  end

  describe "POST /api/v1/auth/register" do
    context "with valid attributes" do
      it "creates a user and returns 201 Created" do
        expect {
          post endpoint, params: valid_params, as: :json
        }.to change(User, :count).by(1)

        expect(response).to have_http_status(:created)

        user = User.find_by!(email: "test@example.com")

        expect(response.parsed_body).to eq(
          {
            "data" => {
              "id" => user.id,
              "email" => user.email
            }
          }
        )

        expect(user.authenticate("password@1")).to be_truthy
      end
    end

    context "with invalid attributes" do
      it "rejects duplicate email" do
        create(:user, email: "test@example.com")

        expect {
          post endpoint, params: valid_params, as: :json
        }.not_to change(User, :count)

        expect(response).to have_http_status(:unprocessable_entity)

        expect(response.parsed_body["errors"])
          .to include("Email has already been taken")
      end

      it "rejects email with different casing" do
        create(:user, email: "test@example.com")

        params = valid_params.deep_merge(
          user: { email: "TEST@EXAMPLE.COM" }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unprocessable_entity)

        expect(response.parsed_body["errors"])
          .to include("Email has already been taken")
      end

      it "rejects missing email" do
        params = valid_params.deep_merge(
          user: { email: nil }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unprocessable_entity)

        expect(response.parsed_body["errors"])
          .to include("Email can't be blank")
      end

      it "rejects missing password" do
        params = valid_params.deep_merge(
          user: {
            password: nil,
            password_confirmation: nil
          }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unprocessable_entity)

        expect(response.parsed_body["errors"])
          .to include("Password can't be blank")
      end

      it "rejects password confirmation mismatch" do
        params = valid_params.deep_merge(
          user: { password_confirmation: "wrong-password" }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unprocessable_entity)

        expect(response.parsed_body["errors"])
          .to include("Password confirmation doesn't match Password")
      end
    end

    context "with malicious mass-assignment attributes" do
      it "does not allow password_digest to be assigned" do
        attacker_digest = SecureRandom.hex(32)

        params = valid_params.deep_merge(
          user: { password_digest: attacker_digest }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:created)

        user = User.find_by!(email: "test@example.com")

        expect(user.password_digest).not_to eq(attacker_digest)
        expect(user.authenticate("password@1")).to be_truthy

        expect(response.parsed_body.dig("data").keys)
          .to contain_exactly("id", "email")
      end
    end
  end
end

Important testing concepts in this spec

1. change(User, :count).by(1) – This verifies the database side effect, not just the HTTP response.

2. as: :json – This tells Rails that we’re sending a JSON request. It also helps test the actual JSON API contract.

3. response.parsed_body – Avoid manually parsing JSON with JSON.parse(response.body) when Rails already provides this helper.

4. deep_merge – Preserves the nested user structure when overriding individual attributes.

5. contain_exactly – Verifies the serialized response contains exactly the permitted attributes, irrespective of ordering.

project structure

Our backend now has:

backend/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ blueprints/
β”‚   β”‚   └── user_blueprint.rb
β”‚   β”‚
β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   └── api/
β”‚   β”‚       └── v1/
β”‚   β”‚           └── registrations_controller.rb
β”‚   β”‚
β”‚   └── models/
β”‚       β”œβ”€β”€ user.rb
β”‚       └── task.rb
β”‚
β”œβ”€β”€ config/
β”‚   └── routes.rb
β”‚
└── spec/
    └── requests/
        └── api/
            └── v1/
                └── registrations_spec.rb

Run: bundle exec rspec spec/requests/api/v1/registrations_spec.rb
Then: bundle exec rspec

API documentation – absolutely, we should have it

I strongly recommend documenting our API using the OpenAPI Specification

Why?

Imagine another developer joins your project. They shouldn’t need to read all your Rails controllers to understand the API. Documentation should tell them:

  • Available endpoints.
  • HTTP methods.
  • Required request parameters.
  • Request and response JSON structures.
  • Authentication requirements.
  • HTTP status codes.
  • Validation errors.
  • Pagination and filtering parameters.

A frontend developer can understand this without knowing anything about Rails.

OpenAPI is a machine-readable contract that describes these API operations, parameters, schemas, security requirements and responses.

Official standard: https://spec.openapis.org/oas/latest.html

rspec-openapi

Generates OpenAPI from existing RSpec request specs. Requires a separate documentation UI.

My recommendation: rspec-openapi + Swagger UI

rspec-openapi – 0.36.0 Β· November 1, 2026

It generates OpenAPI specifications directly from existing RSpec request specs without requiring a special testing DSL.

It has approximately 3.63 million RubyGems downloads and supports OpenAPI 3.0, 3.1 and 3.2. GitHub repository

Swagger UI – Documentation presentation

Displays the generated OpenAPI file as interactive documentation, including endpoint descriptions, parameters, schemas and request testing. Swagger UI website

How will this work?

For example, when we write:

describe "POST /api/v1/auth/register" do
  it "creates a user" do
    post "/api/v1/auth/register",
      params: valid_params,
      as: :json

    expect(response).to have_http_status(:created)
  end
end

We can run: OPENAPI=1 bundle exec rspec

The tool generates:

doc/
└── openapi.yaml

The generated specification can then be loaded by Swagger UI.

One useful feature is that rspec-openapi preserves manual modifications when updating generated documentation. This matters because generated schemas sometimes need human refinement.

Our final tooling decisions

Rails API tooling baseline

ConcernSelected tool
SerializationBlueprinter
API specificationOpenAPI 3.2
Documentation generationrspec-openapi
Documentation UISwagger UI
Backend testingRSpec
Test dataFactoryBot
AuthenticationJWT + opaque refresh token

When should we introduce API documentation?

I’d introduce rspec-openapi after completing our first few request specs. That way, we won’t create documentation for endpoints that are still changing.

Our learning sequence will now be:

  1. Complete registration API and its request specs.
  2. Implement login, JWT response and refresh-token cookie.
  3. Add authenticated Task CRUD endpoints.
  4. Introduce rspec-openapi and generate our first OpenAPI document.
  5. Configure Swagger UI.
  6. Update documentation whenever request contracts change.
  7. Add API documentation generation and validation to GitHub Actions CI.

This also gives us an excellent engineering practice: API tests become part of our API documentation workflow.

Step 4.3.2 – Login API

Authentication implementation

Our endpoint:

POST /api/v1/auth/login

1. Understand the login flow

For this milestone, we’ll generate only the JWT access token. The opaque refresh token and HttpOnly cookie will come next.

2. Create SessionsController

I recommend naming this controller SessionsController.

Why?

A session represents an authenticated user’s interaction with our application. Login, refresh and logout are all part of the session lifecycle.

Create: touch app/controllers/api/v1/sessions_controller.rb

Expected location: app/controllers/api/v1/sessions_controller.rb

Controller: Api::V1::SessionsController

Implement the create action.

A. Rate limiting

Use Rails’ built-in rate limiter:

rate_limit to: 10, within: 3.minutes, only: :create

Rails defaults to IP-based limiting and uses its configured ActiveSupport cache store. It returns HTTP 429 after the limit is exceeded.

For our API, customize the response to JSON:

{
"errors": ["Too many login attempts. Try again later."]
}

Use HTTP 429 Too Many Requests. We’ll later discuss per-account limits and distributed cache configuration for production.

B. Accept login parameters

We need only:

email
password

Create a private method named login_params. Use strong parameters.

Do not permit password_digest, admin, role or other protected attributes.

C. Find and authenticate the User

Use: User.find_by(...)

Then authenticate using: user.authenticate(...)

Remember how has_secure_password works:

  • Correct password returns the User object.
  • Incorrect password returns false.

Handle the case where the email doesn’t exist as well.

Important security requirement: Return exactly the same error message for an unknown email and an incorrect password.

For both: 401 Unauthorized

{
"errors": ["Invalid email or password"]
}

This prevents attackers from using the login endpoint to discover registered email addresses.

D. Generate JWT

Once credentials are valid: Authentication::AccessToken.issue(user)

E. Successful response

Use Blueprinter to serialize the User.

Our response contract:

{
  "data": {
    "access_token": "eyJhbGciOiJIUzI1NiJ9...",
    "token_type": "Bearer",
    "expires_in": 600,
    "user": {
      "id": 1,
      "email": "test@example.com"
    }
  }
}

Return HTTP 200 OK. Use the TTL constant from Authentication::Base instead of hardcoding 600.

Add the route

Open config/routes.rb. Add: post "auth/login", to: "sessions#create"

Inside our existing namespaces:

namespace :api do
  namespace :v1 do
    # Existing registration route
    # New login route
  end
end

Your RSpec request specs

Create: touch spec/requests/api/v1/sessions_spec.rb

Use:

RSpec.describe "API V1 Sessions", type: :request do
  describe "POST /api/v1/auth/login" do
    # Examples
  end
end

I want to cover these scenarios:

ScenarioExpected behaviour
Valid email and password200 OK
Incorrect password401
Non-existent email401
Missing email401
Missing password401
Invalid credentials responseSame generic error
Successful loginReturns valid JWT
JWT payloadCorrect User ID
Response serializationNo password_digest

Three important testing hints

1. Test the actual JWT

After logging in, extract: response.parsed_body.dig("data", "access_token")

Verify it using our existing: Authentication::TokenVerifier.verify(token)

Check that the returned sub matches the logged-in user’s ID.

2. Test security-sensitive response fields

Verify that the response doesn’t contain: password, password_digest

3. Test user enumeration protection

Make two login requests:

  • Existing email with incorrect password.
  • Non-existent email.

Verify both return the same HTTP status and error response. We want consistent external behaviour even though the internal failure reasons differ.

Manual API testing

Start Rails: rails server -p 3000

Try:

curl -i -X POST http://localhost:3000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "login": {
      "email": "test@example.com",
      "password": "password@1"
    }
  }'

Make sure the email belongs to an existing user.

Run RSpec bundle exec rspec spec/requests/api/v1/sessions_spec.rb

Then: bundle exec rspec

I recommend normalizing the email before looking it up, because our User model normalizes emails to lowercase.

backend/app/controllers/api/v1/sessions_controller.rb:

class Api::V1::SessionsController < ApplicationController
  rate_limit to: 10,
             within: 3.minutes,
             only: :create,
             with: -> {
               render json: {
                 errors: ["Too many login attempts. Try again later."]
               }, status: :too_many_requests
             }

  def create
    email = login_params[:email].to_s.strip.downcase
    password = login_params[:password]
    user = User.find_by(email: email)

    unless password.present? && user&.authenticate(password)
      return render json: {
        errors: ["Invalid email or password"]
      }, status: :unauthorized
    end

    access_token = Authentication::AccessToken.issue(user)

    render json: SessionBlueprint.render_as_hash(
      user,
      root: :data,
      access_token: access_token,
      expires_in: Authentication::Base::ACCESS_TOKEN_TTL.to_i
    ), status: :ok
  end

  private

  def login_params
    params.require(:login).permit(:email, :password)
  end
end

Best way to create SessionBlueprint

I recommend a dedicated SessionBlueprint rather than putting login response construction inside the controller.

Why? A login response isn’t just a User. It includes authentication-specific information:

  • Access token.
  • Token type.
  • Expiration.
  • User information.

But we don’t need an ActiveRecord Session model just to serialize this response. Create: touch app/blueprints/session_blueprint.rb

backend/app/blueprints/session_blueprint.rb:

class SessionBlueprint < Blueprinter::Base
  field :access_token do |_user, options|
    options.fetch(:access_token)
  end

  field :token_type do |_user, _options|
    "Bearer"
  end

  field :expires_in do |_user, options|
    options.fetch(:expires_in)
  end

  association :user, blueprint: UserBlueprint do |user, _options|
    user
  end
end

Understand how this works

Notice:

field :access_token do |_user, options|
options.fetch(:access_token)
end

Blueprinter allows us to pass additional options while rendering.

For example:

SessionBlueprint.render_as_hash(
  user,
  root: :data,
  access_token: token,
  expires_in: 600
)

The user is the source object, while access_token and expires_in are additional rendering options. For the association:

association :user, blueprint: UserBlueprint do |user, _options|
  user
end

We reuse the existing UserBlueprint rather than duplicating the User serialization rules. This is supported by Blueprinter’s association and rendering-options APIs.

Our login response contract

Successful login – 200 OK

{
  "data": {
    "access_token": "eyJhbGciOiJIUzI1NiJ9...",
    "token_type": "Bearer",
    "expires_in": 600,
    "user": {
      "id": 1,
      "email": "test@example.com"
    }
  }
}

The JWT is returned to React. The password and password_digest are never serialized.

backend/spec/requests/api/v1/sessions_spec.rb:

require "rails_helper"

RSpec.describe "API V1 Sessions", type: :request do
  let(:endpoint) { "/api/v1/auth/login" }

  let(:user) do
    create(
      :user,
      email: "test@example.com",
      password: "password@1"
    )
  end

  let(:valid_params) do
    {
      login: {
        email: user.email,
        password: "password@1"
      }
    }
  end

  let(:invalid_response) do
    {
      "errors" => ["Invalid email or password"]
    }
  end

  describe "POST /api/v1/auth/login" do
    context "with valid credentials" do
      it "returns 200 OK" do
        post endpoint, params: valid_params, as: :json

        expect(response).to have_http_status(:ok)
      end

      it "returns an access token" do
        post endpoint, params: valid_params, as: :json

        body = response.parsed_body

        expect(body.dig("data", "access_token")).to be_present
        expect(body.dig("data", "token_type")).to eq("Bearer")
        expect(body.dig("data", "expires_in"))
          .to eq(Authentication::Base::ACCESS_TOKEN_TTL.to_i)
      end

      it "returns the authenticated user" do
        post endpoint, params: valid_params, as: :json

        expect(response.parsed_body.dig("data", "user")).to eq(
          {
            "id" => user.id,
            "email" => user.email
          }
        )
      end

      it "generates a valid JWT for the authenticated user" do
        post endpoint, params: valid_params, as: :json

        token = response.parsed_body.dig("data", "access_token")

        payload = Authentication::TokenVerifier.verify(token)

        expect(payload).to be_a(Hash)
        expect(payload["sub"]).to eq(user.id.to_s)
      end

      it "does not expose sensitive user attributes" do
        post endpoint, params: valid_params, as: :json

        body = response.parsed_body

        expect(body.dig("data", "user").keys)
          .to contain_exactly("id", "email")

        expect(body.to_json).not_to include("password_digest")
        expect(body.to_json).not_to include("password")
      end
    end

    context "with invalid credentials" do
      it "rejects an incorrect password" do
        params = valid_params.deep_merge(
          login: { password: "wrong-password" }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unauthorized)
        expect(response.parsed_body).to eq(invalid_response)
      end

      it "rejects a non-existent email" do
        params = {
          login: {
            email: "unknown@example.com",
            password: "password@1"
          }
        }

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unauthorized)
        expect(response.parsed_body).to eq(invalid_response)
      end

      it "rejects a missing email" do
        params = valid_params.deep_merge(
          login: { email: nil }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unauthorized)
        expect(response.parsed_body).to eq(invalid_response)
      end

      it "rejects a missing password" do
        params = valid_params.deep_merge(
          login: { password: nil }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unauthorized)
        expect(response.parsed_body).to eq(invalid_response)
      end

      it "uses the same response for unknown email and incorrect password" do
        invalid_password_params = valid_params.deep_merge(
          login: { password: "wrong-password" }
        )

        post endpoint, params: invalid_password_params, as: :json

        first_response = response.parsed_body

        post endpoint,
             params: {
               login: {
                 email: "unknown@example.com",
                 password: "password@1"
               }
             },
             as: :json

        second_response = response.parsed_body

        expect(first_response).to eq(second_response)
      end
    end

    context "with normalized email" do
      it "allows login using uppercase email" do
        params = valid_params.deep_merge(
          login: { email: "TEST@EXAMPLE.COM" }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:ok)
      end
    end
  end
end

Run: bundle exec rspec spec/requests/api/v1/sessions_spec.rb
Run every spec: bundle exec rspec spec/

What comes next: Refresh Token

Now we have: Completed design JWT generation, verification, registration and login. Our next small milestone is the refresh-token implementation.

We’ll introduce:

app/
β”œβ”€β”€ models/
β”‚   └── refresh_session.rb
β”‚
└── services/
    └── authentication/
        └── refresh_token.rb

The flow will be:

We’ll learn refresh-token rotation, revocation, expiry, cookie configuration, CSRF and RSpec tests.

One architectural point: We won’t put the refresh token in the JSON response. It will be sent through an HttpOnly cookie, while the access JWT remains in React memory.

This keeps our authentication design consistent with the architecture we’ve chosen.

Check Refresh token here (Premium): https://railsdrop.com/create-task-manager-app-refresh-token-implementation/

4. Enable cookies in our API-only Rails application

This is an important configuration step.

Rails API-only applications exclude cookie middleware by default. We must explicitly add it and include the controller cookie module.

A. Update config/application.rb

Inside your Application configuration:

config.middleware.use ActionDispatch::Cookies

B. Update ApplicationController

backend/app/controllers/application_controller.rb:

class ApplicationController < ActionController::API
  include ActionController::Cookies
end

Now Rails controllers can read and write cookies.

C. Configure CORS for React

We’ll need this because:

React: http://localhost:5173
Rails: http://localhost:3000

These are different origins.

Add to your Gemfile:

gem "rack-cors"

Run:

bundle install

Create:

config/initializers/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins ENV.fetch("FRONTEND_ORIGIN", "http://localhost:5173")

    resource "/api/*",
      headers: :any,
      methods: %i[get post patch put delete options],
      credentials: true
  end
end

Important:

  • Never use origins "*" with credentialed requests.
  • credentials: true permits browser credential handling.
  • Use the exact frontend origin.

We’ll use credentials: "include" in React fetch calls later.

12. React integration – remember these requirements

When we build the React API service, the authentication requests must use:

fetch("http://localhost:3000/api/v1/auth/refresh", {
  method: "POST",
  credentials: "include",
});

credentials: "include" is essential because our refresh token is stored in a cookie and the frontend and backend have different origins.

The same option is required for login and logout so the browser can store and send the refresh cookie.

For ordinary task requests, we’ll send:

Authorization: Bearer <access_token>

We’ll keep the access token in React memory, not localStorage.

One security limitation: Logging out revokes the refresh-token family, but an already-issued access JWT remains valid until its 10-minute expiry. Immediate access-token revocation would require additional server-side state, such as a jti denylist or token-version check. We’ll discuss that when implementing authorization.

13. Next: Final backend milestone, then React

Step 4.5 – Protect Task APIs with JWT

We’ll implement only the essentials:

  1. authenticate_request! in ApplicationController.
  2. Extract the Bearer token.
  3. Call TokenVerifier.
  4. Find and set current_user.
  5. Protect Task endpoints.
  6. Scope every query through current_user.tasks.
  7. Add request specs for unauthorized access and cross-user task access.

Then start React

We’ll move to the frontend immediately after this:

  • React application structure.
  • Fluent UI layout.
  • Login and registration.
  • JWT integration.
  • Task list and task details.
  • React hooks, data fetching and caching.

I have deliberately kept the refresh-token implementation complete (even though I can’t work on it completely) but focused. Once the backend security boundary is in place, we can spend most of our remaining learning time on React, Docker and GitHub Actions.

Create Task Manager app: Implement – Rails API, JWT Authentication

In this session let’s get into our applications Authentication section where we decided to move on with JWT token. Here I state that the decision of moving with JWT token is solely for my experience purpose where I already have implemented the token based applications.

The best fit for our application’s authentication system is the Opaque token based authentication. But when we create big applications which has many services connected together and need to be compatible with different platforms/hardwares, jwt is the key for the centralized authentication system.

Step 4.1 – Rails API structure and first endpoint

Before building Task CRUD endpoints, let’s establish our API structure and see how Rails handles HTTP requests.

One important decision: We’ll implement JWT authentication before exposing task data. I don’t want to build an endpoint that returns every user’s tasks and later re-fit authorization.

Understand our API structure

We’ll use versioned API namespaces.

backend/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   β”œβ”€β”€ application_controller.rb
β”‚   β”‚   └── api/
β”‚   β”‚       └── v1/
β”‚   β”‚           └── authentication_controller.rb
β”‚   β”‚
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ user.rb
β”‚   β”‚   └── task.rb
β”‚   β”‚
β”‚   └── ...
β”‚
β”œβ”€β”€ config/
β”‚   └── routes.rb
β”‚
└── spec/
    β”œβ”€β”€ models/
    └── requests/
        └── api/
            └── v1/

Why version the API?

Suppose we eventually release our API to external consumers. We might introduce breaking changes in the future.

/api/v1/tasks
/api/v2/tasks

We can maintain both versions during a migration rather than breaking existing clients.

Understand JWT architecture

JWT stands for JSON Web Token. It is a compact format for securely transmitting claims between parties.

A JWT consists of three parts:

Header example

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload example

{
  "sub": "42",
  "iss": "task_manager_api",
  "aud": "task_manager_web",
  "iat": 1795000000,
  "exp": 1795000600,
  "jti": "unique-token-id"
}

Signature: Generated using the encoded header, encoded payload and signing secret. It allows Rails to detect token modification.

The complete token looks like: xxxxx.yyyyy.zzzzz

Each part is Base64URL encoded, and the signature is cryptographically generated.

Important: JWT is not encrypted by default. Anyone who obtains a JWT can decode its header and payload. The signature protects integrity, not confidentiality. Never put passwords or sensitive personal information in the payload.

Understand the claims we will use

Claims are the information carried inside the JWT payload.

ClaimMeaningOur usage
subSubjectUser ID
issIssuerOur Rails API
audAudienceOur React application
iatIssued atToken creation time
expExpirationToken expiry
jtiJWT IDUnique token identifier

Two important concepts:

sub – Subject – Identifies the user associated with the token.

We’ll use: {
"sub": "42"
}

When Rails receives the token, it can identify user ID 42 after verifying the signature.

exp – Expiration – Defines when the access token expires.

Our initial policy:

10 min – Access token lifetime – Short-lived JWT

7 days – Refresh session lifetime – Initial policy, configurable

We’ll implement refresh-token expiration and rotation separately.

Which signing algorithm should we use?

We’ll start with HS256.

AlgorithmDescription
HS256HMAC using SHA-256 and a shared secret
RS256RSA with SHA-256, using private/public keys
ES256ECDSA with SHA-256

Why HS256?

Our architecture currently has one Rails application that both generates and verifies tokens.

  • Rails has the signing secret.
  • Rails verifies signatures using the same secret.
  • We don’t need public/private key infrastructure yet.

One security rule: the verification algorithm must be explicitly allowlisted. Never trust the alg value supplied in an unverified token header to choose the verification algorithm.

Q) Why use JWT? How we trust the JWT payload/header? JWT vs Opaque token

Read detail here(Premium Content): https://railsdrop.com/why-use-jwt-how-we-trust-the-jwt-payload-header/

Install Ruby JWT gem

We’ll use the official Ruby implementation: https://github.com/jwt/ruby-jwt

From your backend directory: cd backend

Add to your Gemfile:

gem "jwt"

Keep it outside the development/test group because we’ll need it in production too.

Install: bundle install

Verify: bundle info jwt

The gem provides:

JWT.encode(payload, secret, algorithm)
JWT.decode(token, secret, true, algorithm: algorithm)

We’ll use these methods shortly.

Configure the JWT signing secret

This is an important security decision. Never hardcode the JWT secret inside your service class.

Generate a secure secret:

bin/rails secret

Copy the generated value temporarily.

Now edit Rails credentials:

VISUAL="code --wait" bin/rails credentials:edit

Add:

jwt:
  secret_key: YOUR_GENERATED_SECRET

Save and close the editor.

Rails stores credentials encrypted in: config/credentials.yml.enc. The encryption key is stored separately in: config/master.key

The encrypted credentials file can be committed to Git. Never commit master.key. Also, never paste your actual signing secret into our conversation. Later, we’ll configure separate production secrets through deployment/CI environment configuration.

Our authentication service structure

Let’s establish the structure before implementing the login flow.

app/
β”œβ”€β”€ controllers/
β”‚   └── api/
β”‚       └── v1/
β”‚           └── authentication_controller.rb
β”‚
β”œβ”€β”€ services/
β”‚   └── authentication/
β”‚       β”œβ”€β”€ access_token.rb
β”‚       β”œβ”€β”€ token_verifier.rb
β”‚       └── refresh_token.rb
β”‚
└── models/
    β”œβ”€β”€ user.rb
    └── refresh_session.rb

Each component has a separate responsibility.

ComponentResponsibility
AccessTokenGenerate signed JWT
TokenVerifierDecode and verify JWT
AuthenticationControllerLogin, logout and refresh HTTP endpoints
RefreshTokenServiceGenerate, rotate and revoke refresh tokens
RefreshSessionPersist refresh-token session information

We’ll build these individually.

HMAC (Hash-based Message Authentication Code) is a cryptographic technique that combines a secret key and a hash function (such as SHA-256) to verify both the integrity and authenticity of a message.

HS256 (HMAC using SHA-256) is a symmetric cryptographic algorithm used to sign and verify JSON Web Tokens (JWT).

Modified implementation

I want to create a AccessToken class which is clean and not having any constants, error handling code etc. Let’s add a Base class and move the constants and the data which are rarely changes. Also create an Error module in which we store the error related data and will be available across all the classes via mixin.

A. authentication/error.rb

Convert Error into a module.

# frozen_string_literal: true

module Authentication
  module Error
    USER_ERROR = "A persisted user is required"
    SECRET_MISSING = "JWT signing secret is missing"

    def secret_length(length)
      "JWT signing secret must be at least #{length} bytes"
    end
  end
end

Why a module?

We want to reuse error messages and the secret_length helper across authentication classes.

We’ll use extend Error in Base, rather than include Error, because our helper needs to be available in class-method context.

B. authentication/base.rb

Move the common payload generation and secret management here.

# frozen_string_literal: true

require "securerandom"

module Authentication
  class Base
    extend Error

    ALGORITHM = "HS256"
    ISSUER = "task_manager_api"
    AUDIENCE = "task_manager_web"
    ACCESS_TOKEN_TTL = 10.minutes
    SECRET_BYTE_SIZE = 32

    class << self
      def payload
        now = Time.current.to_i

        {
          iss: ISSUER,
          aud: AUDIENCE,
          iat: now,
          exp: now + ACCESS_TOKEN_TTL.to_i,
          jti: SecureRandom.uuid
        }
      end

      private

      def signing_secret
        secret = Rails.application.credentials.dig(:jwt, :secret_key)

        raise KeyError, Error::SECRET_MISSING if secret.blank?

        if secret.bytesize < SECRET_BYTE_SIZE
          raise KeyError, secret_length(SECRET_BYTE_SIZE)
        end

        secret
      end
    end
  end
end

Notice two important things:

  1. payload is now a class method. Subclasses inherit it.
  2. signing_secret is a private class method. Subclasses can use it internally without exposing it as a public API.

C. authentication/access_token.rb

Your AccessToken class becomes much cleaner.

module Authentication
  class AccessToken < Base
    class << self
      def issue(user)
        unless user&.persisted?
          raise ArgumentError, Error::USER_ERROR
        end

        token_payload = payload.merge(sub: user.id.to_s)

        JWT.encode(token_payload, signing_secret, Base::ALGORITHM)
      end
    end
  end
end

This achieves what I wanted:

  • Constants stay in Base.
  • Errors stay in Error.
  • Common payload generation stays in Base.
  • AccessToken only handles access-token generation.

Also, sub is now a string, as required for the JWT Subject claim.

Q) Error: NameError:
uninitialized constant #<Class:Authentication::AccessToken>::ALGORITHM
# ./app/services/authentication/access_token.rb:11

When I modified the line:

JWT.encode(token_payload, signing_secret, ALGORITHM) TO
JWT.encode(token_payload, signing_secret, Base::ALGORITHM) it works. Why?

Find the answer here(Premium): https://railsdrop.com/ruby-constant-lookup-inside-a-singleton-class-class-self/

Modified RSpec specifications

I’d keep two spec files. We should test the shared Base functionality separately and test the actual JWT through its public issue method.

A. spec/services/authentication/base_spec.rb

require "rails_helper"

RSpec.describe Authentication::Base do
  describe ".payload" do
    let(:payload) { described_class.payload }

    it "includes the common JWT claims" do
      expect(payload.keys).to include(
        :iss, :aud, :iat, :exp, :jti
      )

      expect(payload).not_to have_key(:sub)
    end

    it "sets the correct issuer and audience" do
      expect(payload[:iss]).to eq("task_manager_api")
      expect(payload[:aud]).to eq("task_manager_web")
    end

    it "sets the expiration relative to issued time" do
      expect(payload[:exp] - payload[:iat]).to eq(10.minutes.to_i)
    end

    it "generates a unique JWT ID" do
      first_payload = described_class.payload
      second_payload = described_class.payload

      expect(first_payload[:jti]).not_to eq(second_payload[:jti])
    end
  end
end

Note: we’re testing the common functionality, not private implementation details.

B. spec/services/authentication/access_token_spec.rb

require "rails_helper"

RSpec.describe Authentication::AccessToken do
  let(:user) { create(:user) }
  let(:secret) { Rails.application.credentials.dig(:jwt, :secret_key) }

  describe ".issue" do
    context "with a persisted user" do
      let(:token) { described_class.issue(user) }

      it "generates a JWT string" do
        expect(token).to be_a(String)
        expect(token.split(".").size).to eq(3)
      end

      it "contains the correct JWT header" do
        _payload, header = JWT.decode(
          token,
          secret,
          true,
          algorithm: described_class::ALGORITHM
        )

        expect(header["alg"]).to eq("HS256")
      end

      it "contains the correct claims" do
        payload, = JWT.decode(
          token,
          secret,
          true,
          {
            algorithm: described_class::ALGORITHM,
            iss: described_class::ISSUER,
            verify_iss: true,
            aud: described_class::AUDIENCE,
            verify_aud: true,
            required_claims: %w[sub iss aud iat exp jti]
          }
        )

        expect(payload["sub"]).to eq(user.id.to_s)
        expect(payload["iss"]).to eq("task_manager_api")
        expect(payload["aud"]).to eq("task_manager_web")
        expect(payload["iat"]).to be_a(Integer)
        expect(payload["exp"] - payload["iat"]).to eq(10.minutes.to_i)
        expect(payload["jti"]).to be_present
      end

      it "generates a different jti for every token" do
        first_token = described_class.issue(user)
        second_token = described_class.issue(user)

        first_payload = JWT.decode(first_token, secret, true, algorithm: "HS256").first
        second_payload = JWT.decode(second_token, secret, true, algorithm: "HS256").first

        expect(first_payload["jti"]).not_to eq(second_payload["jti"])
      end
    end

    context "without a persisted user" do
      it "raises an error when user is nil" do
        expect {
          described_class.issue(nil)
        }.to raise_error(ArgumentError, Authentication::Error::USER_ERROR)
      end

      it "raises an error when user is not persisted" do
        expect {
          described_class.issue(build(:user))
        }.to raise_error(ArgumentError, Authentication::Error::USER_ERROR)
      end
    end
  end
end

The JWT.decode calls explicitly configure HS256 and validate the issuer, audience and required claims. This follows the Ruby JWT library’s verification API.

Why did we remove the Base payload test from AccessToken?

Your original test was:

payload = described_class.send(:payload, user)

There are two problems:

  • payload was an instance method.
  • send bypasses Ruby’s private-method visibility.

We don’t need that approach anymore.

Instead, our AccessToken spec tests the actual generated JWT and inspects its verified payload.

This is a stronger test of the service’s public behaviour.

Final directory structure

app/services/authentication/
β”œβ”€β”€ base.rb
β”œβ”€β”€ error.rb
└── access_token.rb

spec/services/authentication/
β”œβ”€β”€ base_spec.rb
└── access_token_spec.rb

And as I decided, our future refresh-token implementation will be: app/services/authentication/refresh_token.rb

Run the tests

bundle exec rspec spec/services/authentication/

One security note: these tests verify JWT issuance. We haven’t yet implemented incoming token verification, which is where signature trust, expiry, issuer, audience and algorithm allowlisting must all be enforced.

My recommendation: Keep this structure. It is small, maintainable and leaves room for future authentication functionality without turning AccessToken into a large service class.

Next we’ll build Authentication::TokenVerifier using this same architecture.

JWT decoding and verification

1. What exactly are we verifying?

Remember our generated token: header.payload.signature

When Rails receives this token, it must verify:

CheckWhat are we protecting against?
SignatureToken modification or forged token
AlgorithmAlgorithm substitution attacks
Expiration (exp)Use of expired tokens
Issuer (iss)Tokens from an untrusted issuer
Audience (aud)Tokens intended for another application
Issued at (iat)Invalid or future issuance timestamps
Required claimsMissing identity or security information

The Ruby JWT library supports these checks directly through JWT.decode. We must explicitly specify the accepted algorithm.

2. Understand JWT.decode

We’ve already used this in our specs: JWT.decode(token, secret, true, options)

Let’s understand the arguments:

ArgumentMeaning
tokenIncoming JWT string
secretSigning secret
trueEnable signature verification
optionsAlgorithm and claim verification configuration

The return value is: [
decoded_payload,
decoded_header
]

For example: payload, header = JWT.decode(...)

Important: Never do this in production: JWT.decode(token, secret, false)

That disables signature verification. Decoding a token is not the same as trusting it.

3. Create TokenVerifier

Create:

touch app/services/authentication/token_verifier.rb
touch spec/services/authentication/token_verifier_spec.rb

Our intended structure:

app/services/authentication/
β”œβ”€β”€ base.rb
β”œβ”€β”€ error.rb
β”œβ”€β”€ access_token.rb
β”œβ”€β”€ token_verifier.rb
└── refresh_token.rb

We’ll follow your existing design:

module Authentication
  class TokenVerifier < Base
    class << self
      def verify(token)
        # Your implementation
      end
    end
  end
end

Decide what verify should return

I recommend this contract:

InputResult
Valid JWTVerified payload Hash
Expired JWTnil
Invalid signaturenil
Invalid issuernil
Invalid audiencenil
Malformed JWTnil
Missing tokennil

Why return the payload instead of the User object? Because these are separate responsibilities:

  • TokenVerifier verifies cryptographic authenticity and claims.
  • The authentication layer identifies the corresponding User.
  • The authorization layer decides whether that user can access a resource.

This separation will become useful when we implement current_user

Our implementation requirements

Implement Authentication::TokenVerifier.verify(token).

A. Validate the input – Reject missing or blank tokens.

B. Decode and verify the token – Use JWT.decode with:

  • Signature verification enabled.
  • Base::ALGORITHM as the fixed algorithm.
  • Base::ISSUER as the expected issuer.
  • Base::AUDIENCE as the expected audience.
  • Expiration verification enabled.
  • Issued-at verification enabled.
  • Required claims: sub, iss, aud, iat, exp, jti.

Your decoding options should conceptually look like:

{
  algorithm: Base::ALGORITHM,
  iss: Base::ISSUER,
  verify_iss: true,
  aud: Base::AUDIENCE,
  verify_aud: true,
  verify_expiration: true,
  verify_iat: true,
  required_claims: %w[sub iss aud iat exp jti]
}

See the https://github.com/jwt/ruby-jwt for the current option names and behaviour.

C. Return the verified payload

JWT.decode returns an array. We only need the first element. Return the payload after successfully validating the token. Also ensure the sub claim is a non-empty string.

D. Handle JWT errors

An invalid token should not crash our Rails application. For the current ruby-jwt 3.3 error hierarchy, use:

rescue JWT::TokenError
  nil

Version note: JWT::TokenError was introduced in 3.3.0. Older versions can use JWT::DecodeError, which remains a compatible superclass for decoding errors. You can check your installed version using: bundle info jwt

Do not rescue every StandardError. A missing signing secret or an application programming error should not silently become an invalid-token response.

RSpec assignment

Create these examples in: spec/services/authentication/token_verifier_spec.rb

Use:

RSpec.describe Authentication::TokenVerifier do
  describe ".verify" do
    # Your examples
  end
end

Implement these seven scenarios.

TestExpected result
Valid JWT generated by AccessTokenReturns Hash
Correct subjectsub matches User ID
Expired tokenReturns nil
Wrong signing secretReturns nil
Wrong issuerReturns nil
Wrong audienceReturns nil
Malformed token / nil tokenReturns nil

Useful testing hints

For the valid token:

user = create(:user)
token = Authentication::AccessToken.issue(user)

For creating an expired token in your spec, use the same signing secret but give it an expiration timestamp in the past.

For testing an invalid signature, generate a token using a different secret.

For issuer and audience tests, generate tokens with incorrect claims, but sign them using the legitimate application secret. This ensures we’re testing claim validation rather than signature failure.

We don’t need to use mocks or stubs yet. These tests should use real JWT generation and verification.

6. How our authentication flow will eventually work

Notice that successful JWT verification alone doesn’t prove that the user still exists or that their account is active. We’ll implement those checks in the next authentication milestone. Also, we’ll later introduce rate_limit and authorization checks in the relevant controllers.

TokenVerifier implementation

backend/app/services/authentication/token_verifier.rb:

module Authentication
  class TokenVerifier < Base
    class << self
      def verify(token)
        return nil unless token.is_a?(String) && token.present?

        options = {
          algorithm: Base::ALGORITHM,
          iss: Base::ISSUER,
          verify_iss: true,
          aud: Base::AUDIENCE,
          verify_aud: true,
          verify_expiration: true,
          verify_iat: true,
          verify_jti: true,
          required_claims: %w[sub iss aud iat exp jti]
        }

        payload, = JWT.decode(token, signing_secret, true, options)

        return nil unless valid?(payload["sub"])
        return nil unless valid?(payload["jti"])

        payload
      rescue JWT::TokenError
        nil
      end

      private

      def valid?(item)
        item.is_a?(String) && item.present?
      end
    end
  end
end

Why these changes?

CodeResponsibility
token.is_a?(String)Reject unexpected input types
signing_secretReuse secret validation from Base
algorithmOnly accept HS256
verify_issValidate trusted issuer
verify_audValidate intended audience
verify_expirationReject expired tokens
verify_iatReject invalid/future issuance times
verify_jtiVerify JWT ID
required_claimsReject missing claims
valid_subject?Ensure a valid user identifier
valid_jti?Ensure a non-empty token identifier
rescue JWT::TokenErrorConvert invalid JWTs into nil

One important distinction: We only rescue JWT token errors. If our signing secret is missing or misconfigured, the application should raise a configuration error rather than pretending the incoming token is invalid.

Complete RSpec specifications

backend/spec/services/authentication/token_verifier_spec.rb:

require "rails_helper"

RSpec.describe Authentication::TokenVerifier do
  let(:user) { create(:user) }
  let(:secret) { Rails.application.credentials.dig(:jwt, :secret_key) }
  let(:valid_token) { Authentication::AccessToken.issue(user) }

  let(:decoded_payload) do
    JWT.decode(
      valid_token,
      secret,
      true,
      algorithm: Authentication::Base::ALGORITHM
    ).first
  end

  describe ".verify" do
    context "with a valid token" do
      it "returns the verified payload" do
        result = described_class.verify(valid_token)

        expect(result).to be_a(Hash)
        expect(result["sub"]).to eq(user.id.to_s)
        expect(result["iss"]).to eq(Authentication::Base::ISSUER)
        expect(result["aud"]).to eq(Authentication::Base::AUDIENCE)
      end

      it "returns the jti claim" do
        result = described_class.verify(valid_token)

        expect(result["jti"]).to be_present
      end
    end

    context "with an invalid token" do
      it "returns nil for blank tokens" do
        expect(described_class.verify(nil)).to be_nil
        expect(described_class.verify("")).to be_nil
        expect(described_class.verify("  ")).to be_nil
      end

      it "returns nil for non-string input" do
        expect(described_class.verify(123)).to be_nil
      end

      it "returns nil for malformed tokens" do
        expect(described_class.verify("invalid-token")).to be_nil
      end

      it "returns nil for expired tokens" do
        expired_payload = decoded_payload.merge(
          "exp" => 1.minute.ago.to_i
        )

        token = JWT.encode(
          expired_payload,
          secret,
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end

      it "returns nil for an invalid signature" do
        token = JWT.encode(
          decoded_payload,
          SecureRandom.hex(32),
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end

      it "returns nil for an incorrect issuer" do
        payload = decoded_payload.merge(
          "iss" => "untrusted_api"
        )

        token = JWT.encode(
          payload,
          secret,
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end

      it "returns nil for an incorrect audience" do
        payload = decoded_payload.merge(
          "aud" => "another_application"
        )

        token = JWT.encode(
          payload,
          secret,
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end

      it "returns nil when a required claim is missing" do
        payload = decoded_payload.except("sub")

        token = JWT.encode(
          payload,
          secret,
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end

      it "returns nil when issued at is in the future" do
        payload = decoded_payload.merge(
          "iat" => 5.minutes.from_now.to_i
        )

        token = JWT.encode(
          payload,
          secret,
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end
    end
  end
end

We’ll test real token generation and verification rather than mocking JWT.

Run the specifications:

bundle exec rspec spec/services/authentication/token_verifier_spec.rb

Then run both JWT service specs:

bundle exec rspec spec/services/authentication/

Understand an important distinction before our next step

Our verifier returns:

{
  "sub" => "42",
  "iss" => "task_manager_api",
  "aud" => "task_manager_web",
  "iat" => 1795000000,
  "exp" => 1795000600,
  "jti" => "..."
}

It does not return a User object.

The next authentication layer will do: User.find_by(id: payload["sub"])

Why query the database if JWT is self-contained? Because we need to know whether:

  • The user still exists.
  • The account is active.
  • The user has been disabled.

JWT signature verification proves that the token is authentic. It does not guarantee that the associated user is still allowed to access the application.

We’ll implement this in our authentication controller/base controller.

Next milestone: Registration and Login APIs, including password verification with has_secure_password, issuing JWTs, Rails rate_limit and request specs. We’ll also ensure that a user cannot access another user’s tasks by changing an ID.

Software ArchitectΒ Guide: Designing a RESTful API for a 🌐 Multi-Tenant Blogging Platform

Building a multi-tenant blogging platform requires thoughtful design of the API to ensure clarity, scalability, and security. In this post, we’ll explore a RESTful API design including versioning, nested resources, and authentication, using clear examples and best practices.


🧩 Understanding the Requirements

Before diving into endpoints, let’s break down what the platform supports:

  • Multiple tenants (e.g., organizations, teams)
  • Each tenant has users
  • Users can create blogs, and each blog has posts
  • Posts can have comments
  • Authentication is required

πŸ“ Versioning

We’ll use URI-based versioning:

/api/v1/

This helps manage breaking changes cleanly.


πŸ” Authentication

We’ll use token-based authentication (e.g., JWT or API keys). Each request must include:

Authorization: Bearer <token>

πŸ“Œ Base URL

https://api.blogcloud.com/api/v1

πŸ“š API Endpoint Design

πŸ”Έ Tenants

Tenants are top-level entities.

  • GET /tenants – List all tenants (admin only)
  • POST /tenants – Create a new tenant
  • GET /tenants/:id – Show tenant details
  • PATCH /tenants/:id – Update tenant
  • DELETE /tenants/:id – Delete tenant

πŸ”Έ Users (Scoped by tenant)

  • GET /tenants/:tenant_id/users – List users for tenant
  • POST /tenants/:tenant_id/users – Create user
  • GET /tenants/:tenant_id/users/:id – Show user
  • PATCH /tenants/:tenant_id/users/:id – Update user
  • DELETE /tenants/:tenant_id/users/:id – Delete user

πŸ”Έ Blogs (Belong to users)

  • GET /tenants/:tenant_id/users/:user_id/blogs – List blogs
  • POST /tenants/:tenant_id/users/:user_id/blogs – Create blog
  • GET /tenants/:tenant_id/users/:user_id/blogs/:id – Show blog
  • PATCH /tenants/:tenant_id/users/:user_id/blogs/:id – Update blog
  • DELETE /tenants/:tenant_id/users/:user_id/blogs/:id – Delete blog

πŸ”Έ Posts (Belong to blogs)

  • GET /blogs/:blog_id/posts – List posts
  • POST /blogs/:blog_id/posts – Create post
  • GET /blogs/:blog_id/posts/:id – Show post
  • PATCH /blogs/:blog_id/posts/:id – Update post
  • DELETE /blogs/:blog_id/posts/:id – Delete post

πŸ”Έ Comments (Belong to posts)

  • GET /posts/:post_id/comments – List comments
  • POST /posts/:post_id/comments – Add comment
  • DELETE /posts/:post_id/comments/:id – Delete comment

❓Question: what is the full url of comments?

No, the full URL for comments should not be:

https://api.blogcloud.com/api/v1/tenants/:tenant_id/users/:user_id/blogs/posts/:post_id/comments

That nesting is too deep and redundant, because:

  • By the time you’re at a post, you already implicitly know which blog/user/tenant it’s under (assuming proper authorization).
  • Posts have unique IDs across the system (or at least within blogs), so we don’t need the entire hierarchy in every request.

βœ… Correct RESTful URL for Comments

If your post_id is unique (or unique within a blog), the cleanest design is:

https://api.blogcloud.com/api/v1/posts/:post_id/comments

or, if you prefer to keep blog_id context:

https://api.blogcloud.com/api/v1/blogs/:blog_id/posts/:post_id/comments

Use that second version only if post_id is not globally unique, and you need the blog context.

πŸ” Recap of Comments Endpoints

ActionHTTP VerbEndpoint
List commentsGET/api/v1/posts/:post_id/comments
Create commentPOST/api/v1/posts/:post_id/comments
Delete commentDELETE/api/v1/posts/:post_id/comments/:id

🧠 Design Rule of Thumb

  • βœ… Keep URLs meaningful and shallow.
  • ❌ Don’t over-nest resources unless it’s needed to enforce scoping or clarify context.

πŸ“₯ Example: Create a Blog Post

Request:

POST /blogs/123/posts
Authorization: Bearer <token>
Content-Type: application/json

{
  "title": "Why REST APIs Still Matter",
  "body": "In this post, we explore the benefits of RESTful design..."
}

Response:

201 Created
{
  "id": 456,
  "title": "Why REST APIs Still Matter",
  "body": "In this post, we explore the benefits of RESTful design...",
  "created_at": "2025-07-03T10:00:00Z"
}


βœ… Best Practices Followed

  • Nesting: Resources are nested to show ownership (e.g., blogs under users).
  • Versioning: Prevents breaking old clients.
  • Consistency: Same verbs and JSON structure everywhere.
  • Authentication: Every sensitive request requires a token.

🧠 Final Thoughts

Designing a RESTful API for a multi-tenant app like a blogging platform requires balancing structure and simplicity. By properly scoping resources, using versioning, and enforcing auth, you build an API that’s powerful, secure, and easy to maintain.

Bonus Tip: Document your API using tools like Swagger/OpenAPI to make onboarding faster for new developers.

You are an awesome Architect πŸš€

Securing Your Rails 8 API with Token -Based Vs JWT Authentication πŸ”‘

Modern web and mobile applications demand secure APIs. Traditional session-based authentication falls short in stateless architectures like RESTful APIs. This is where Token-Based Authentication and JWT (JSON Web Token) shine. In this blog post, we’ll explore both approaches, understand how they work, and integrate them into a Rails 8 application.

πŸ” 1. What is Token-Based Authentication?

Token-based authentication is a stateless security mechanism where the server issues a unique, time-bound token after validating a user’s credentials. The client stores this token (usually in local storage or memory) and sends it along with each API request via HTTP headers.

Key Concepts:

  • Stateless: No session is stored on the server.
  • Scalable: Ideal for distributed systems.
  • Tokens can be opaque (random strings).

πŸƒΊ Algorithms used:

  • Token generation commonly uses SecureRandom.

What is SecureRandom?

SecureRandom is a Ruby module that generates cryptographically secure random numbers and strings. It uses operating system facilities (like /dev/urandom on Unix or CryptGenRandom on Windows) to generate high-entropy values that are safe for use in security-sensitive contexts like tokens, session identifiers, and passwords.

For example:

SecureRandom.hex(32) # generates a 64-character hex string (256 bits)

In Ruby, if you encounter the error:

(irb):5:in '<main>': uninitialized constant SecureRandom (NameError)
Did you mean?  SecurityError

It means the SecureRandom module hasn’t been loaded. Although SecureRandom is part of the Ruby Standard Library, it’s not automatically loaded in every environment. You need to explicitly require it.

Solution

Add the following line before using SecureRandom:

require 'securerandom'

Then you can use:

SecureRandom.hex(16)  # => "a1b2c3d4e5f6..."

Why This Happens

Ruby does not auto-load all standard libraries to save memory and load time. Modules like SecureRandom, CSV, OpenURI, etc., must be explicitly required if you’re working outside of Rails (like in plain Ruby scripts or IRB).

In a Rails environment, require 'securerandom' is typically handled automatically by the framework.

Tip for IRB

If you’re experimenting in IRB (interactive Ruby shell), just run:

require 'securerandom'
SecureRandom.uuid  # or any other method

This will eliminate the NameError.

Why 256 bits?

A 256-bit token offers a massive keyspace of 2^256 combinations, making brute-force attacks virtually impossible. The higher the bit-length, the better the resistance to collision and guessing attacks. Most secure tokens range between 128 and 256 bits. While larger tokens are more secure, they consume more memory and storage.

⚠️ Drawbacks:

  • SecureRandom tokens are opaque and must be stored on the server (e.g., in a database) for validation.
  • Token revocation requires server-side tracking.

Implementing Token-Based Authentication in Rails 8

Step 1: Generate User Model

rails g model User email:string password_digest:string token:string
rails db:migrate

Step 2: Add Secure Token

# app/models/user.rb
has_secure_password
has_secure_token :token

Step 3: Authentication Controller

# app/controllers/api/v1/sessions_controller.rb
class Api::V1::SessionsController < ApplicationController
  def create
    user = User.find_by(email: params[:email])
    if user&.authenticate(params[:password])
      user.regenerate_token
      render json: { token: user.token }, status: :ok
    else
      render json: { error: 'Invalid credentials' }, status: :unauthorized
    end
  end
end

Step 4: Protect API Endpoints

# app/controllers/application_controller.rb
class ApplicationController < ActionController::API
  before_action :authenticate_user!

  private

  def authenticate_user!
    token = request.headers['Authorization']&.split(' ')&.last
    @current_user = User.find_by(token: token)
    render json: { error: 'Unauthorized' }, status: :unauthorized unless @current_user
  end
end


πŸ” 2. What is JWT (JSON Web Token)?

JWT is an open standard for secure information exchange, defined in RFC 7519.

πŸ”— What is RFC 7519?

RFC 7519 is a specification by the IETF (Internet Engineering Task Force) that defines the structure and rules of JSON Web Tokens. It lays out how to encode claims in a compact, URL-safe format and secure them using cryptographic algorithms. It standardizes the way information is passed between parties as a JSON object.

Check: https://datatracker.ietf.org/doc/html/rfc7519

πŸ“ˆ Structure of JWT:

A JWT has three parts:

  1. Header: Specifies the algorithm used (e.g., HS256) and token type (JWT).
  2. Payload: Contains claims (e.g., user_id, exp).
  3. Signature: Validates the token integrity using a secret or key.

Example:

eyeJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE2ODk5OTk5OTl9.Dr2k1ehxw7qBKi_Oe-JogBxy...

πŸš€ Why 3 Parts?

  • The Header informs the verifier of the cryptographic operations applied.
  • The Payload is the actual data transferred.
  • The Signature protects the data and ensures that the token hasn’t been modified.

This makes JWT self-contained, tamper-resistant, and easily verifiable without a server-side lookup.

βš–οΈ JWT Algorithms in Detail

πŸ“ HS256 (HMAC SHA-256)

HS256 stands for HMAC with SHA-256. It is a symmetric algorithm, meaning the same secret is used for signing and verifying the JWT.

  • HMAC: Hash-based Message Authentication Code combines a secret key with the hash function.
  • SHA-256: A 256-bit secure hash function that produces a fixed-length output.
⚑ Why JWT uses HS256?
  • It’s fast and computationally lightweight.
  • Ensures that only someone with the secret can produce a valid signature.
  • Ideal for internal applications where the secret remains safe.

If your use case involves public key encryption, you should use RS256 (RSA) which uses asymmetric key pairs.

🌟 Advantages of JWT over Basic Tokens

FeatureToken-BasedJWT
Self-containedNoYes
Verifiable without DBNoYes
Expiry built-inNoYes
Tamper-proofLowHigh
ScalableMediumHigh

🧬 Deep Dive: The Third Part of a JWT β€” The Signature

πŸ“Œ What is the Third Part?

The third part of a JWT is the signature. It ensures data integrity and authenticity.

Structure of a JWT:

<base64url-encoded header>.<base64url-encoded payload>.<base64url-encoded signature>

Each section is Base64URL-encoded and joined with .

πŸ” How is the Signature Generated?

The signature is created using a cryptographic algorithm like HS256, and it’s built like this:

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret_key
)

βœ… Example:

Assume the following:

Header: {
  "alg": "HS256",
  "typ": "JWT"
}
Payload: {
  "user_id": 1,
  "exp": 1717777777
}
Secret key: "my$ecretKey"

  1. Base64URL encode header and payload:
    header = Base64.urlsafe_encode64('{"alg":"HS256","typ":"JWT"}') # eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

    payload = Base64.urlsafe_encode64('{"user_id":1,"exp":1717777777}') # eyJ1c2VyX2lkIjoxLCJleHAiOjE3MTc3Nzc3Nzd9
  2. Concatenate them with a period: data = "#{header}.#{payload}"
  3. Sign it with HMAC SHA-256 using your secret:
    signature = OpenSSL::HMAC.digest('sha256', 'my$ecretKey', data)
  4. Base64URL encode the result: Base64.urlsafe_encode64(signature)

Now your JWT becomes:

<encoded-header>.<encoded-payload>.<encoded-signature>

🎯 Why Is the Signature Crucial?
  • Tamper Detection: If someone changes the payload (e.g., user_id: 1 to user_id: 9999), the signature will no longer match, and verification will fail.
  • Authentication: Only the party with the secret key can generate a valid signature. This confirms the sender is trusted.
  • Integrity: Ensures the content of the token hasn’t been altered between issuance and consumption.
πŸ” What If Signature Is Invalid?

When the server receives the token:

JWT.decode(token, secret, true, { algorithm: 'HS256' })

If the signature doesn’t match the header + payload:

  • It raises an error (JWT::VerificationError)
  • The request is rejected with 401 Unauthorized

βš™οΈ Why Use HS256?

  • HS256 (HMAC with SHA-256) is fast and secure for symmetric use cases.
  • Requires only a single shared secret for encoding and decoding.
  • Ideal for internal systems or when you fully control both the issuer and verifier.

Great questions! Let’s break them down in simple, technical terms:


1️⃣ What is a Digital Signature in JWT?

A digital signature is a way to prove that a piece of data has not been tampered with and that it came from a trusted source.

πŸ” In JWT:

  • The signature is created using:
    • The Header (e.g. {"alg": "HS256", "typ": "JWT"})
    • The Payload (e.g. {"user_id": 1, "exp": 1717777777})
    • A secret key (known only to the issuer)

βœ… Is it encryption?

❌ No, the signature does not encrypt the data.
βœ… It performs a one-way hash-based verification using algorithms like HMAC SHA-256.

HMACSHA256(base64url(header) + "." + base64url(payload), secret)

The result is a hash (signature), not encrypted data.

πŸ“Œ What does “digitally signed” mean?

When a JWT is digitally signed, it means:

  • The payload was not altered after being issued
  • The token was created by someone who knows the secret key

2️⃣ Can JWT Transfer Big JSON Payloads?

Technically, yes, but with trade-offs.

🧾 Payload in JWT

The payload can be any JSON object:

{
  "user_id": 1,
  "role": "admin",
  "permissions": ["read", "write", "delete"],
  "data": { "long_array": [...], "details": {...} }
}

🚧 But Watch Out:

ConcernDescription
πŸ”„ Token SizeJWTs are often stored in headers or cookies. Big payloads increase HTTP request size.
πŸ” Not EncryptedAnyone who gets the token can read the payload unless it’s encrypted.
πŸ’Ύ StorageBrowsers and mobile clients have limits (e.g., cookie size = ~4KB).
🐒 PerformanceBigger payloads = slower parsing, transfer, and validation.

3️⃣ Can We Encrypt a JWT?

Yes, but that requires JWE β€” JSON Web Encryption (not just JWT).

✨ JWT β‰  Encrypted

A normal JWT is:

  • Signed (to prove authenticity & integrity)
  • Not encrypted (anyone can decode and read payload)
πŸ” If You Want Encryption:

Use JWE (RFC 7516), which:

  • Encrypts the payload
  • Uses algorithms like AES, RSA-OAEP, etc.

However, JWE is less commonly used, as it adds complexity and processing cost.

βœ… Summary
FeatureJWT (Signed)JWE (Encrypted)
Data readable?YesNo
Tamper-proof?YesYes
Confidential?NoYes
Commonly used?βœ… Yes⚠️ Less common
AlgorithmHMAC/RS256 (e.g. HS256)AES/RSA

πŸ” What does “one-way hash-based verification using HMAC SHA-256” mean?

Let’s decode this phrase:

πŸ’‘ HMAC SHA-256 is:

  • HMAC = Hash-based Message Authentication Code
  • SHA-256 = Secure Hash Algorithm, 256-bit output

When combined:

HMAC SHA-256 = A cryptographic function that creates a hash (fingerprint) of some data using a secret key.

It does NOT encrypt the data. It does NOT encode the data. It just creates a fixed-length signature to prove authenticity and integrity.

πŸ”’ One-Way Hashing (vs Encryption)

ConceptIs it reversible?PurposeExample Algo
πŸ”‘ Encryptionβœ… Yes (with key)Hide dataAES, RSA
πŸ§ͺ Hashing❌ NoProve data hasn’t changedSHA-256
✍️ HMAC❌ NoSign data w/ secretHMAC SHA256

πŸ” How HMAC SHA-256 is used in JWT (Detailed Example)

Let’s take:

header  = {"alg":"HS256","typ":"JWT"}
payload = {"user_id":123,"exp":1717700000}
secret  = "my$ecretKey"

πŸ”Ή Step 1: Base64Url encode header and payload

base64_header  = Base64.urlsafe_encode64(header.to_json)
# => "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"

base64_payload = Base64.urlsafe_encode64(payload.to_json)
# => "eyJ1c2VyX2lkIjoxMjMsImV4cCI6MTcxNzcwMDAwMH0"

πŸ”Ή Step 2: Concatenate them with a dot

data = "#{base64_header}.#{base64_payload}"
# => "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjMsImV4cCI6MTcxNzcwMDAwMH0"

πŸ”Ή Step 3: Generate Signature using HMAC SHA-256

require 'openssl'
require 'base64'

signature = OpenSSL::HMAC.digest('sha256', secret, data)
# => binary format

encoded_signature = Base64.urlsafe_encode64(signature).gsub('=', '')
# => This is the third part of JWT
# => e.g., "NLoeHhY5jzUgKJGKJq-rK6DTHCKnB7JkPbY3WptZmO8"

βœ… Final JWT:

<header>.<payload>.<signature>

Anyone receiving this token can:

  • Recompute the signature using the same secret key
  • If it matches the one in the token, it’s valid
  • If it doesn’t match, the token has been tampered

❓ Is SHA-256 used for encoding or encrypting?

❌ SHA-256 is not encryption.
❌ SHA-256 is not encoding either.
βœ… It is a hash function: one-way and irreversible.

It’s used in HMAC to sign data (prove data integrity), not to encrypt or hide data.

βœ… Summary:

PurposeSHA-256 / HMAC SHA-256
Encrypts data?❌ No
Hides data?❌ No (use JWE for that)
Reversible?❌ No
Used in JWT?βœ… Yes (for signature)
Safe?βœ… Very secure if secret is strong

🎯 First: The Big Misunderstanding β€” Why JWT Isn’t “Encrypted”

JWT is not encrypted by default.

It is just encoded + signed.
You can decode the payload, but you cannot forge the signature.

🧠 Difference Between Encoding, Encryption, and Hashing

ConceptPurposeReversible?Example
EncodingMake data safe for transmissionβœ… YesBase64
EncryptionHide data from unauthorized eyesβœ… Yes (with key)AES, RSA
HashingVerify data hasn’t changed❌ NoSHA-256, bcrypt

πŸ”“ Why can JWT payload be decoded?

Because the payload is only Base64Url encoded, not encrypted.

Example:

{
  "user_id": 123,
  "role": "admin"
}

When sent in JWT, it becomes:

eyJ1c2VyX2lkIjoxMjMsInJvbGUiOiJhZG1pbiJ9

βœ… You can decode it with any online decoder. It’s not private, only structured and verifiable.

πŸ” Then What Protects the JWT?

The signature is what protects it.

  • It proves the payload hasn’t been modified.
  • The backend signs it with a secret key (HMAC SHA-256 or RS256).
  • If anyone tampers with the payload and doesn’t have the key, they can’t generate a valid signature.

🧾 Why include the payload inside the JWT?

This is the brilliant part of JWT:

  • The token is self-contained.
  • You don’t need a database lookup on every request.
  • You can extract data like user_id, role, permissions right from the token!

βœ… So yes β€” it’s just a token, but a smart token with claims (data) you can trust.

This is ideal for stateless APIs.

πŸ’‘ Then why not send payload in POST body?

You absolutely can β€” and often do, for data-changing operations (like submitting forms). But that’s request data, not authentication info.

JWT serves as the proof of identity and permission, like an ID card.

You put it in the Authorization header, not the body.

πŸ“¦ Is it okay to send large payloads in JWT?

Technically, yes, but not recommended. Why?

  • JWTs are sent in every request header β€” that adds bloat.
  • Bigger tokens = slower transmission + possible header size limits.
  • Keep payload minimal: only what’s necessary (user id, roles, permissions, exp).

If your payload is very large, use a token to reference it in DB or cache, not store everything in the token.

⚠️ If the secret doesn’t match?

Yes β€” that means someone altered the token (probably the payload).

  • If user_id was changed to 999, but they can’t recreate a valid signature (they don’t have the secret), the backend rejects the token.

πŸ” Then When Should We Encrypt?

JWT only signs, but not encrypts.

If you want to hide the payload:

  • Use JWE (JSON Web Encryption) β€” a different standard.
  • Or: don’t put sensitive data in JWT at all.

πŸ” Summary: Why JWT is a Big Deal

  • βœ… Self-contained authentication
  • βœ… Stateless (no DB lookups)
  • βœ… Signed β€” so payload can’t be tampered
  • ❌ Not encrypted β€” anyone can see payload
  • ⚠️ Keep payload small and non-sensitive

🧠 One Last Time: Summary Table

TopicJWTPOST Body
Used forAuthentication/identitySubmitting request data
Data typeClaims (user_id, role)Form/input data
Seen by user?Yes (Base64-encoded)Yes
SecuritySignature w/ secretHTTPS
Stored where?Usually in browser (e.g. localStorage, cookie)N/A

Think of JWT like a sealed letter:

  • Anyone can read the letter (payload).
  • But they can’t forge the signature/stamp.
  • The receiver checks the signature to verify the letter is real and unmodified.

🧨 Yes, JWT Payload is Visible β€” and That Has Implications

The payload of a JWT is only Base64Url encoded, not encrypted.

This means anyone who has the token (e.g., a user, a man-in-the-middle without HTTPS, or a frontend dev inspecting in the browser) can decode it and see:

{
  "user_id": 123,
  "role": "admin",
  "permissions": ["read", "write", "delete"],
  "email": "user@example.com"
}

πŸ” Is This a Security Risk?

It depends on what you put inside the payload.

βœ… Safe things to include:

  • user_id
  • exp (expiration timestamp)
  • Minimal role or scope info like "role": "user"

❌ Do not include sensitive data:

  • Email addresses (if private)
  • Password hashes (never!)
  • Credit card info
  • Internal tokens or database keys
  • Personally Identifiable Info (PII)

πŸ”Ž So Why Do People Still Use JWT?

JWT is great when used correctly:

  • It doesn’t prevent others from reading the payload, but it prevents them from modifying it (thanks to the signature).
  • It allows stateless auth without needing a DB lookup on every request.
  • It’s useful for microservices where services can verify tokens without a central auth store.

🧰 Best Practices for JWT Payloads

  1. Treat the payload as public data.
    • Ask yourself: β€œIs it okay if the user sees this?”
  2. Never trust the token blindly on the client.
    • Always verify the signature and claims server-side.
  3. Use only identifiers, not sensitive context.
    • For example, instead of embedding full permissions: { "user_id": 123, "role": "admin" } fetch detailed permissions on the backend based on role.
  4. Encrypt the token if sensitive data is needed.
    • Use JWE (JSON Web Encryption), or
    • Store sensitive data on the server and pass only a reference (like a session id or user_id).

πŸ“Œ Bottom Line

JWT is not private. It is only protected from tampering, not from reading.

So if you use it in your app, make sure the payload contains only safe, public information, and that any sensitive logic (like permission checks) happens on the server.


πŸš€ Integrating JWT in Rails 8

Step 1: Add Gem

gem 'jwt'

Step 2: Generate Secret Key

# config/initializers/jwt.rb
JWT_SECRET = Rails.application.credentials.jwt_secret || 'your_dev_secret_key'

Step 3: Authentication Logic

# app/services/json_web_token.rb
class JsonWebToken
  def self.encode(payload, exp = 24.hours.from_now)
    payload[:exp] = exp.to_i
    JWT.encode(payload, JWT_SECRET, 'HS256')
  end

  def self.decode(token)
    body = JWT.decode(token, JWT_SECRET, true, { algorithm: 'HS256' })[0]
    HashWithIndifferentAccess.new body
  rescue
    nil
  end
end

Step 4: Sessions Controller for JWT

# app/controllers/api/v1/sessions_controller.rb
class Api::V1::SessionsController < ApplicationController
  def create
    user = User.find_by(email: params[:email])
    if user&.authenticate(params[:password])
      token = JsonWebToken.encode(user_id: user.id)
      render json: { jwt: token }, status: :ok
    else
      render json: { error: 'Invalid credentials' }, status: :unauthorized
    end
  end
end

Step 5: Authentication in Application Controller

# app/controllers/application_controller.rb
class ApplicationController < ActionController::API
  before_action :authenticate_request

  def authenticate_request
    header = request.headers['Authorization']
    token = header.split(' ').last if header
    decoded = JsonWebToken.decode(token)
    @current_user = User.find_by(id: decoded[:user_id]) if decoded
    render json: { error: 'Unauthorized' }, status: :unauthorized unless @current_user
  end
end

🌍 How Token-Based Authentication Secures APIs

πŸ”’ Benefits:

  • Stateless: Scales well
  • Works across domains
  • Easy to integrate with mobile/web clients
  • JWT is tamper-proof and verifiable

⚑ Drawbacks:

  • Token revocation is hard without server tracking (esp. JWT)
  • Long-lived tokens can be risky if leaked
  • Requires HTTPS always

πŸ“† Final Thoughts

For most Rails API-only apps, JWT is the go-to solution due to its stateless, self-contained nature. However, for simpler setups or internal tools, basic token-based methods can still suffice. Choose based on your app’s scale, complexity, and security needs.


Happy coding! πŸš€