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.

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! πŸš€

Guide: RailsΒ 8 API Application – Authentication πŸ” mechanisms | Sample Rails API app with Rspec Test cases

When building a Rails API app, you typically need token-based authentication instead of cookie-based sessions (which are more common in full-stack Rails apps). Here are the most common authentication mechanisms you can use in a Rails API-only application:

πŸ” 1. Token-Based Authentication

Most Common & Recommended for APIs

a. JWT (JSON Web Tokens)

  • Gems: jwt, knock, devise-jwt
  • How it works: After login, the server issues a JWT token which the client must include in the Authorization header (Bearer <token>) in subsequent requests.
  • Pros:
    • Stateless, scalable.
    • Widely supported across mobile and frontend frameworks.
  • Cons:
    • Tokens can’t be invalidated easily without extra measures (e.g., a blacklist).

b. Token-based Auth with Devise + TokenAuthenticatable

  • Gems: devise_token_auth
  • Uses Devise under the hood.
  • Stores tokens on the server (in DB), enabling logout and token revocation.
  • Compatible with React Native and SPAs.

πŸ” 2. OAuth 2.0 / OmniAuth (for Third-party Logins)

  • Gems: omniauth, doorkeeper
  • Use when you want users to log in via:
    • Google
    • Facebook
    • GitHub
  • Doorkeeper is often used to implement OAuth 2 provider (if you’re exposing your API to other apps).
  • Best when integrating external identity providers.

πŸ” 3. API Key Authentication

  • Useful for machine-to-machine communication or when exposing APIs to third-party developers.
  • Each user/client is assigned a unique API key.
  • Example: Authorization: Token token=abc123
  • You store the API key in the DB and verify it on each request.
  • Lightweight and easy to implement.

πŸ” 4. HTTP Basic Authentication

  • Simple and built-in with Rails (authenticate_or_request_with_http_basic).
  • Not suitable for production unless combined with HTTPS and only used for internal/testing tools.

πŸ‘‰πŸ» Choosing the Right Auth Mechanism

Use CaseRecommended Method
Mobile app or frontend SPAJWT (devise-jwt / knock)
Internal API between servicesAPI key
Want email/password with token authdevise_token_auth
External login via Google/GitHubomniauth + doorkeeper
OAuth2 provider for third-party devsdoorkeeper
Quick-and-dirty internal authHTTP Basic Auth

πŸ”„ How JWT Authentication Works β€” Step by Step

1. User Logs In

  • The client (e.g., React app, mobile app) sends a POST /login request with email/password.
  • Your Rails API validates the credentials.
  • If valid, it generates a JWT token and sends it back to the client.
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

2. Client Stores the Token

  • The client stores the token in localStorage, sessionStorage, or memory (for SPAs), or a secure storage for mobile apps.

3. Client Sends Token on Requests

  • For any subsequent request to protected resources, the client includes the JWT in the Authorization header:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

4. Server Verifies the Token

  • Rails extracts the token, decodes it using a secret key, and verifies:
    • The signature is valid.
    • The token is not expired.
    • The user ID (or sub claim) is valid.

If everything checks out, the request is allowed to proceed.

5. Token Expiration

  • Tokens usually include an exp (expiration) claim, e.g., 15 minutes, 1 hour, etc.
  • After expiration, the client must log in again or use a refresh token flow if supported.

πŸ”’ Security: Is JWT Secure?

JWT can be secure, if used correctly. Here’s a breakdown:

βœ… Security Benefits

FeatureWhy It Helps
StatelessNo session storage needed; scales easily
SignedThe token is signed (HMAC or RSA), so it can’t be tampered with
CompactSent in headers; easy to pass around
Exp claimTokens expire automatically after a period

⚠️ Security Considerations

IssueDescriptionMitigation
Token theftIf an attacker steals the token, they can impersonate the user.Always use HTTPS. Avoid storing tokens in localStorage if possible.
No server-side revocationTokens can’t be invalidated until they expire.Use short-lived access tokens + refresh tokens or token blacklist (DB).
Long token lifespanLonger expiry means higher risk if leaked.Keep exp short (e.g., 15–30 min). Use refresh tokens if needed.
Poor secret handlingIf your secret key leaks, anyone can forge tokens.Store your JWT_SECRET in environment variables, never in code.
JWT stored in localStorageSusceptible to XSS attacks in web apps.Use HttpOnly cookies when possible, or protect against XSS.
Algorithm confusionAttacker could force a weak algorithm.Always validate the algorithm (alg) on decoding. Use only HMAC or RSA.

πŸ§ͺ Example Token (Decoded)

A typical JWT has three parts:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJ1c2VyX2lkIjoxLCJleHAiOjE3MDAwMDAwMDB9.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Breakdown:

  1. Header (Base64-encoded JSON)
{
  "alg": "HS256",
  "typ": "JWT"
}

  1. Payload
{
  "user_id": 1,
  "exp": 1700000000
}

  1. Signature
  • HMAC-SHA256 hash of header + payload + secret key.

πŸ›‘ Best Practices for JWT in Rails API

  • Use devise-jwt or knock to handle encoding/decoding securely.
  • Set short token lifetimes (exp claim).
  • Use HTTPS only.
  • Consider implementing refresh tokens for session continuation.
  • Avoid token storage in localStorage unless you trust your frontend.
  • Rotate secrets periodically (invalidate tokens when secrets change).

Now Let’s create a sample Rails API application and test what we learned.

🧱 Sample Rails API web app: Prerequisites

  • A Rails 8 app with --api mode enabled: rails new my_api_app --api
  • A User model with email and password_digest.
  • We’ll use bcrypt for password hashing.

βœ… Step 1: Add Required Gems

In your Gemfile:

gem 'jwt'
gem 'bcrypt'

Then run:

bundle install

βœ… Step 2: Generate the User Model

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

In app/models/user.rb:

class User < ApplicationRecord
  has_secure_password
end

Now you can create users with secure passwords.

βœ… Step 3: Create JWT Helper Module

Create a service object or helper to encode/decode tokens.

app/lib/json_web_token.rb (create the lib folder if needed):

# app/lib/json_web_token.rb
class JsonWebToken
  SECRET_KEY = Rails.application.credentials.secret_key_base

  def self.encode(payload, exp = 24.hours.from_now)
    payload[:exp] = exp.to_i
    JWT.encode(payload, SECRET_KEY)
  end

  def self.decode(token)
    decoded = JWT.decode(token, SECRET_KEY)[0]
    HashWithIndifferentAccess.new(decoded)
  rescue JWT::DecodeError => e
    nil
  end
end

βœ… Step 4: Create the Authentication Controller

rails g controller auth

app/controllers/auth_controller.rb:

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

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

βœ… Step 5: Protect Other Endpoints with Authentication

Make a reusable authenticate_request method.

app/controllers/application_controller.rb:

class ApplicationController < ActionController::API
  before_action :authenticate_request

  attr_reader :current_user

  private

  def authenticate_request
    header = request.headers['Authorization']
    token = header.split(' ').last if header.present?

    if token
      decoded = JsonWebToken.decode(token)
      @current_user = User.find_by(id: decoded[:user_id]) if decoded
    end

    render json: { error: 'Unauthorized' }, status: :unauthorized unless @current_user
  end
end

Now all your controllers inherit this behaviour unless you skip_before_action.

βœ… Step 6: Add Routes

config/routes.rb:

Rails.application.routes.draw do
  post '/login', to: 'auth#login'

  get '/profile', to: 'users#profile' # Example protected route
end

βœ… Step 7: Example Protected Controller

rails g controller users

app/controllers/users_controller.rb:

class UsersController < ApplicationController
  def profile
    render json: { id: current_user.id, email: current_user.email }
  end
end

πŸ§ͺ Test It Out (Example)

Step 1: Create a User (via Rails Console)

User.create!(email: "test@example.com", password: "password123")

Step 2: Login via POST /login

POST /login
Content-Type: application/json

{
  "email": "test@example.com",
  "password": "password123"
}

Response:

{ "token": "eyJhbGciOi..." }

Step 3: Use Token in Authenticated Request

GET /profile
Authorization: Bearer eyJhbGciOi...

πŸ”’ Extras You Might Add Later

  • Token expiration errors
  • Refresh tokens
  • Token revocation (e.g., a blacklist table)
  • Roles/permissions inside the token (e.g., admin claims)

Let’s now write RSpec tests for the JWT-based authentication flow we just set up in your Rails API app.

Assumptions

  • You already have:
    • A User model with email and password_digest
    • An AuthController with login
    • A UsersController with a protected profile action
    • JWT auth logic in JsonWebToken

πŸ”§ Step 1: Add RSpec & Factory Bot

In your Gemfile (if not already added):

group :development, :test do
  gem 'rspec-rails'
  gem 'factory_bot_rails'
end

group :test do
  gem 'faker'
end

Then install:

bundle install
rails generate rspec:install


🏭 Step 2: Setup Factory for User

spec/factories/users.rb:

FactoryBot.define do
  factory :user do
    email { Faker::Internet.email }
    password { 'password123' }
    password_confirmation { 'password123' }
  end
end


πŸ§ͺ Step 3: Auth Request Specs

spec/requests/auth_spec.rb:

require 'rails_helper'

RSpec.describe 'Authentication', type: :request do
  let!(:user) { create(:user, password: 'password123') }

  describe 'POST /login' do
    context 'with valid credentials' do
      it 'returns a JWT token' do
        post '/login', params: { email: user.email, password: 'password123' }

        expect(response).to have_http_status(:ok)
        expect(JSON.parse(response.body)).to include('token')
      end
    end

    context 'with invalid credentials' do
      it 'returns unauthorized' do
        post '/login', params: { email: user.email, password: 'wrong' }

        expect(response).to have_http_status(:unauthorized)
        expect(JSON.parse(response.body)).to include('error')
      end
    end
  end
end


πŸ”’ Step 4: Profile (Protected) Request Specs

spec/requests/users_spec.rb:

require 'rails_helper'

RSpec.describe 'Users', type: :request do
  let!(:user) { create(:user) }
  let(:token) { JsonWebToken.encode(user_id: user.id) }

  describe 'GET /profile' do
    context 'with valid token' do
      it 'returns user profile' do
        get '/profile', headers: { 'Authorization' => "Bearer #{token}" }

        expect(response).to have_http_status(:ok)
        json = JSON.parse(response.body)
        expect(json['email']).to eq(user.email)
      end
    end

    context 'without token' do
      it 'returns unauthorized' do
        get '/profile'
        expect(response).to have_http_status(:unauthorized)
      end
    end

    context 'with invalid token' do
      it 'returns unauthorized' do
        get '/profile', headers: { 'Authorization' => 'Bearer invalid.token' }
        expect(response).to have_http_status(:unauthorized)
      end
    end
  end
end

πŸ“¦ Final Tips

  • Run tests with: bundle exec rspec
  • You can stub JsonWebToken.decode in unit tests if needed to isolate auth logic.