Create Task Manager app: Create Task CRUD supported by JWT authentication

Now I will complete the backend authentication boundary and Task APIs. After this, we’ll move to React.

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. Ruby on Rails Guides

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.

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.


# frozen_string_literal: true

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.