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.

Implement Task Manager application with Ruby on Rails backend, React frontend, Postgresql, Rspec, Docker and Github Actions

Let’s create an application for managing Tasks that are created by different users. Let’s use React UI for quick data response. The app consists of CRUD operations of Tasks, User Authentication using JWT-Tokens, User Authorization for their particular tasks.

Technology stack

Here’s the list of technology stack we use in our application.

LayerTechnologyPurpose
BackendRuby on Rails 8.1+REST API
DatabasePostgreSQLPersistent storage
FrontendReactUI
LanguageTypeScriptStatic typing
Build toolViteFrontend development/build
UI libraryFluent UI React v9Components and styling
HTTPFetch API initiallyAPI communication
Server cacheTanStack QueryAPI data caching
Global stateRedux ToolkitShared client-side state
Testing backendRSpecAPI and model tests
Testing frontendVitest + React Testing LibraryComponent tests
ContainersDocker + Docker ComposeContainerization
CI/CDGitHub ActionsAutomation and deployment

Check our ruby current version.

$ ruby -v

ruby 3.4.1 (2024-12-25 revision 48d4efcb85)

Check the security patches and updates of our version.

https://www.ruby-lang.org/en/downloads/releases

Then update the latest compatible version.

$ mise use -g ruby@3.4.12

(2026-10-23 revision 366f5fdc00)

To uninstall Ruby using mise, run mise uninstall ruby@ to delete a specific installed version.

$ mise uninstall ruby@3.4.1

Install latest ruby version that you need.

Switch between versions globally:

$ mise use -g ruby@3.4.12

$ mise use -g ruby@4.0.9

Check all needed versions exists:

ruby -v
gem -v
rails -v
node -v
npm -v
psql --version

Check Postgres versions available here: https://www.postgresql.org/download/macosx/

Download the one of the latest one if you have currently installed the old version.

$ brew install postgresql@18

Installing postgresql@18
==> Pouring postgresql@18--18.7.arm64_tahoe.bottle.tar.gz
Warning: postgresql@18 was installed but not linked because postgresql@14 is already linked.
To link this version, run:
brew link postgresql@18

$ brew link postgresql@18
Unlinking /opt/homebrew/Cellar/postgresql@14/14.17_1... 2165 symlinks removed.
Linking /opt/homebrew/Cellar/postgresql@18/18.7... 812 symlinks created.
$ psql --version
psql (PostgreSQL) 18.7 (Homebrew)

Update node js:

$ node -v
v24.14.0

install the latest Long-Term Support release

$ nvm install --lts
Installing latest LTS version.
Downloading and installing node v26.13.1...
Downloading https://nodejs.org/dist/v26.13.1/node-v26.13.1-darwin-arm64.tar.xz...
Computing checksum with sha256sum
Checksums matched!
Now using node v26.13.1 (npm v11.20.0)

Create app folder:

$ mkdir rails-react-task-manager
$ cd rails-react-task-manager
$ git init -b main

We want to manage the backend, frontend, Docker configuration and CI/CD workflows in one repository.

Update ruby gems:

A new release of RubyGems is available: 4.0.20 β†’ 4.0.24!
See https://github.com/ruby/rubygems/blob/v4.0.24/CHANGELOG.md for the changes since 4.0.20.
Run `gem update --system 4.0.24` to update your installation

Install Rails:

check rails newest versions: https://rubygems.org/gems/rails/versions

$ gem install rails -v '~> 8.1.0'

Note: Pessimistic version constraint. Using -v “~> 8.1.0” installs the latest patch release within the 8.1 series (such as 8.1.4.1) while avoiding unintended jumps to future minor or major versions

Reopen the shell and check:

Create a github repository

name it: rails-react-task-manager

$ git remote add origin git@github.com:<username>/rails-react-task-manager.git

Problem 1:

The first problem I faced was the command rails new already has the folders: .git, .github, .gitattributes, .gitignore etc inside rails app.

So when I try to push the rails app:

git add backend/
error: 'backend/' does not have a commit checked out
error: unable to index file 'backend/'
fatal: adding files failed

This happens because Rails automatically initializes a Git repository when you run rails new.

Solution: Keep only one Git repository

Since we’re building a monorepo, we want Git initialized only at the project root.

Remove only the nested Git metadata:

rm -rf backend/.git
TypeWhen to Use It Example
choreUpgrading packages, libraries, or runtime versions chore: update Node.js version or chore(deps): bump lodash
featAdding a new feature or capability for the user.feat: add user login via OAuth
fixPatching a bug in the application code.fix: resolve crash on checkout page
refactorRestructuring production code without changing its behavior.refactor: simplify auth helper logic
docsUpdating READMEs, comments, or API guides.docs: add setup instructions
styleFixing formatting, whitespace, or missing semicolons.style: format files with Prettier
testAdding or updating unit and integration tests.test: add unit tests for cart total
build / ciMaking dedicated changes to build systems or CI pipelines (used by teams that prefer stricter categories over chore).ci: cache node_modules in pipeline

Problem 2:

Accessing the Rails url at: http://localhost:3000/

Started GET "/" for ::1 at 2026-11-15 

ActiveRecord::StatementInvalid (PG::InvalidParameterValue: ERROR:  invalid value for parameter "TimeZone": "UTC"
)
Caused by: PG::InvalidParameterValue (ERROR:  invalid value for parameter "TimeZone": "UTC"
)

Information for: ActiveRecord::StatementInvalid (PG::InvalidParameterValue: ERROR:  invalid value for parameter "TimeZone": "UTC"
):

Solution: check which PostgreSQL server is actually running

psql --version
brew services list
brew services stop postgresql@14
brew services restart postgresql@18
# then do
rails db:prepare -t # recommended

Restart the rails server. Also check:

curl -i http://localhost:3000/up

Install RSpec

Add RSpec to Gemfile

group :development, :test do
  gem "rspec-rails", "~> 8.1"
end

Install the gem

cd backend
bundle install
bundle exec rspec --version

Generate RSpec configuration

 rails g rspec:install
      create  .rspec
      create  spec
      create  spec/spec_helper.rb
      create  spec/rails_helper.rb
FileResponsibility
.rspecDefault command-line options for RSpec
spec_helper.rbGeneral RSpec configuration
rails_helper.rbRails-specific test configuration

Important distinction:

spec_helper.rb can be used for tests that don’t require Rails.

rails_helper.rb loads the Rails application and integrates Rails testing functionality.

Verify:

bundle exec rspec
No examples found.

Finished in 0.00022 seconds (files took 0.05449 seconds to load)
0 examples, 0 failures

Minitest is still present: Your Rails application probably already has: backend/test/. That’s because Rails generated its default Minitest structure. We’ll configure Rails generators to use RSpec automatically, so that when we generate a model, Rails creates: spec/models/task_spec.rb instead of: test/models/task_test.rb. We’ll also decide how to handle the existing Minitest files cleanly.

Configure Rails generators to use RSpec

Currently, Rails uses Minitest as its default testing framework. For example, when you generate a model: bin/rails generate model Task title:string, Rails normally generates: app/models/task.rb
test/models/task_test.rb

But we want: app/models/task.rb
spec/models/task_spec.rb

RSpec Rails integrates with Rails generators to do exactly this.

Open: backend/config/application.rb and add:

config.generators do |g|
  g.test_framework :rspec
end

Important: This does not remove Minitest or disable its test runner. It changes the default generator behaviour.

We don’t want to generate our actual Task model just to test the configuration.

Instead, use Rails --pretend option:

rails g model Task title:string --pretend
      invoke  active_record
      create    db/migrate/20261115171837_create_tasks.rb
      create    app/models/task.rb
      invoke    rspec
      create      spec/models/task_spec.rb

Rspec Structure:

spec/
β”œβ”€β”€ models/
β”‚   └── task_spec.rb
β”‚
β”œβ”€β”€ requests/
β”‚   └── api/
β”‚       └── v1/
β”‚           └── tasks_spec.rb
β”‚
β”œβ”€β”€ services/
β”‚   └── authentication/
β”‚
β”œβ”€β”€ jobs/
β”œβ”€β”€ factories/
β”‚
β”œβ”€β”€ spec_helper.rb
└── rails_helper.rb

For our Rails API, we’ll primarily use request specs instead of controller specs. A request spec tests the application from the HTTP client’s perspective. This lets us test the complete API behaviour rather than testing controller methods in isolation. RSpec Rails recommends request specs as the higher-level alternative to controller specs.

For example:

HTTP Request
    ↓
Router
    ↓
Controller
    ↓
Authentication
    ↓
Authorization
    ↓
Model / Database
    ↓
HTTP Response

Understand the structure of an RSpec test

An RSpec test typically consists of four important building blocks:

RSpec syntaxPurpose
RSpec.describeDefines the top-level example group
describeGroups related examples
contextDescribes a particular condition or scenario
itDefines an individual test example
expectDefines an expectation
toSpecifies the expected matcher

Let’s look at a simple example.

RSpec.describe "RSpec basics" do
  describe "equality matcher" do
    it "compares two values" do
      result = 2 + 3

      expect(result).to eq(5)
    end
  end
end

Understand each line

RSpec.describe "RSpec basics" – Creates an example group. This is the outermost container for our tests.

describe "equality matcher" – Groups tests related to equality. You can nest multiple describe blocks to organize tests logically.

it "compares two values" – Defines an individual test example. The string describes the expected behaviour. RSpec uses it when displaying test results.

expect(result).to eq(5) – This is the actual expectation.

  • expect(result) – the actual value.
  • to – tells RSpec we’re checking a positive expectation.
  • eq(5) – matcher checking whether the actual value equals 5 using Ruby’s == operator.

If the expectation fails, RSpec reports a failure with the actual and expected values.

Understand RSpec matchers

Matchers are one of the most important parts of RSpec.

They determine how RSpec compares actual and expected values.

Here are some commonly used matchers:

MatcherPurposeExample
eqValue equality (==)eq(10)
beObject identity (equal?)be(true)
includeCollection contains valueinclude("Rails")
be_nilChecks nilbe_nil
be_emptyChecks empty collectionbe_empty
be_truthyChecks truthinessbe_truthy
be_falseyChecks falsinessbe_falsey
matchRegular expression matchingmatch(/rails/i)
raise_errorChecks raised exceptionraise_error(ArgumentError)

A particularly important distinction: expect("Rails").to eq("Rails")

This checks value equality. Whereas: expect(object).to be(other_object)

This checks whether both references point to the same object. Don’t confuse eq and be. You can also write negative expectations: expect(result).not_to eq(10) This verifies that the result isn’t equal to 10.

One principle to remember: Good tests should make the behaviour obvious, minimize duplicated setup and remain independent of one another. That’s the mindset I want you to develop while learning RSpec.

Understand describe vs context

They look similar, but they serve slightly different organizational purposes. Consider a future Task model.

RSpec.describe Task do
  describe "validations" do
    context "when title is present" do
      # Examples go here
    end

    context "when title is missing" do
      # Examples go here
    end
  end
end

Preferred convention:

  • describe: What behaviour are we testing?
  • context: Under what circumstances are we testing it?
  • it: What should happen?

Technically, describe and context create the same kind of RSpec example group. The difference is semantic and improves readability.

hands-on exercise

Let’s create a temporary learning spec. We aren’t creating the Task model or touching the database yet. From your backend directory:

mkdir spec/learning
touch spec/learning/rspec_basics_spec.rb

Start with the previous equality example. Now add your own examples to cover these requirements:

Exercise 1 – Equality

Write an example that checks whether 10 + 20 equals 30.

Exercise 2 – Collection

Given: languages = ["Ruby", "JavaScript", "Python"]

Write an expectation that verifies the array includes "Ruby".

Exercise 3 – Nil

Given a variable whose value is nil, verify that it is nil.

Exercise 4 – Boolean

Given a variable whose value is false, verify that it is exactly false.

Exercise 5 – Negative expectation

Verify that the languages array does not include "Java".

Execute your tests: bundle exec rspec spec/learning/rspec_basics_spec.rb

For more readable output: bundle exec rspec spec/learning/rspec_basics_spec.rb --format documentation , The documentation formatter displays the example descriptions and their results.

Refer:

https://rspec.info/features/3-13/rspec-expectations/built-in-matchers/equality

https://rspec.info/features/3-13/rspec-expectations/built-in-matchers/include

https://rspec.info/features/3-12/rspec-core/helper-methods/let

RSpec.describe "Rspec Basics learning" do
  describe "Equality" do
    let(:languages) { ["Ruby", "JavaScript", "Python"] }

    it "check addition" do
      expect(10 + 20).to eq(30)
    end

    it "include in the list" do
      expect(languages).to include "Ruby"
    end

    it "checks nil value" do
      nil_value = nil
      expect(nil_value).to be_nil
    end

    it "checks false value" do
      false_value = false
      true_value = true
      expect(false_value).to be false
      expect(false_value).to be_falsey
      expect(true_value).to be_truthy
      expect(true_value).to be true
    end

    it "checks negative expectation" do
      expect(languages).not_to include "Scala" 
    end
  end
end

# run
$ rspec spec/

Note:
be false vs be_falsey These are different expectations.

expect(false).to be false 
expect(false).to be_falsey
expect(nil).to be_falsey
expect(true).to be_truthy

be_truthy accepts anything other than false or nil. be false checks that the value is exactly false. be_falsey accepts either false or nil. let is lazily evaluated and memoized within an individual example.

We’ll apply these concepts to our first actual Rails model spec. No need to rush into FactoryBot yet. We should understand native RSpec first.

RSpec hooks: before, after, let and let!

This is one of the most frequently used parts of RSpec in real Rails projects. When writing model and request specs, we often need to prepare test data before executing an example.

For example:

  • Create a user before testing authentication.
  • Create a task before testing task updates.
  • Prepare some data before testing associations.
  • Clean up resources after an example.

RSpec provides hooks and helper methods for this.

before hook

RSpec.describe "Task" do
  before do
    puts "Running before hook"
  end

  it "checks something" do
    puts "Running example"
  end

  it "checks something else" do
    puts "Running another example"
  end
end

# output
Running before hook
Running example

Running before hook
Running another example

before executes before every example by default. These are equivalent:

before do
  # Setup
end

# and

before(:each) do
  # Setup
end

When do we use it?

When every example needs some common setup. For example, imagine we need a variable initialized before each test.

Imagine we have 10 test examples and every example requires the same initial setup.

# Without hooks, you might repeat:

it "example 1" do
  languages = ["Ruby", "JavaScript"]
  # Test logic
end

it "example 2" do
  languages = ["Ruby", "JavaScript"]
  # Test logic
end

# This creates unnecessary duplication. RSpec provides hooks to solve this problem.

Understand let vs before

This distinction is particularly important.

beforelet
Setup hookDefines a helper method
Executes automaticallyExecutes only when referenced
Runs before every example by defaultEvaluates once per example
Useful for setup actionsUseful for reusable test data

after hook: after executes after each example.

after(:each) do
  puts "Cleaning up"
end

Typical use cases:

  • Cleaning up temporary resources.
  • Restoring modified environment variables.
  • Closing external resources.
  • Removing temporary files.

RSpec Rails and transactional tests will handle much of our database cleanup automatically, so we shouldn’t manually delete every test record in after

let – lazy evaluation

Let’s understand its behaviour: let(:languages) { ["Ruby", "JavaScript", "Python"] } . And if you call it multiple times within the same example, RSpec reuses its cached value. This is called lazy evaluation and memoization.

Hands-on exercise

Let’s create another learning spec: touch spec/learning/rspec_setup_hooks_spec.rb

RSpec.describe "RSpec setup hooks" do
  let(:execution_log) { [] }

  let(:languages) do
    execution_log << :languages_created
    ["Ruby", "JavaScript", "Python"]
  end

  before(:each) do
    execution_log << :before_hook
  end

  # Write your examples here
  it "Test lazy evaluation" do
    puts "execution_log: #{execution_log}"
  end
  
  it "Access let variable and check lazy evaluation when referenced" do
    expect(languages).to include("Ruby")
    puts "execution_log: #{execution_log}"
  end
  
  it "Access let variables twice within this example and verify lazy loading" do
    expect(languages).to include("Python")
    expect(languages).not_to include("Rust")
    puts "execution_log: #{execution_log}"
  end
end

We’ll now cover three important RSpec concepts that you’ll use extensively when writing Rails model specs and request specs:

  1. let! – eager evaluation.
  2. subject – defining the primary object under test.
  3. before(:all) vs before(:each) – setup lifecycle and execution order.

RSpec execution lifecycle

1. let vs let!

We already understand let. let!(:user) { "Abhilash" } The ! changes the behaviour.

# let - Lazy

Start example
    |
    v
Before hook
    |
    v
Execute example
    |
    v
Access user?
   /    \
  Yes     No
  |       |
Evaluate  Never
# let! - Eager

Start example
    |
    v
Execute let! setup
    |
    v
Before hooks (according to declaration order)
    |
    v
Execute example

Technically, let! is implemented by defining a let helper and registering a before hook that invokes it.

When should we use let!?

Consider a Rails model spec. Suppose we want to test whether a user has three tasks. We need those three tasks to exist before the example executes. This is a good use case for let!. let!(:task) { create(:task) }

We’ll eventually use FactoryBot’s create method here.

My recommendation: Prefer let by default. Use let! when the setup must happen before the example, regardless of whether the helper is explicitly accessed.

2. subject – the primary object under test

This is another important RSpec concept. Suppose we’re testing a method that normalizes a task title. Instead of repeatedly creating or referencing the main result, we can define it using subject.

subject(:normalized_title) do
  title.strip.downcase
end

Now we can use: expect(normalized_title).to eq("learn rails")

Why use subject?

Imagine testing a Task model with many examples. The primary object being tested is usually a Task instance. We can define:

subject(:task) do
  Task.new(title: "Learn Rails")
end

Then use: expect(task).to be_valid

Notice the difference:

letsubject
Defines reusable test dataDefines the primary object under test
Can define multiple helpersUsually one primary subject per example group
Access using its nameAccess using its name or subject
Lazy and memoizedLazy and memoized

A named subject such as subject(:task) also creates a helper called task.

What is the implicit subject?

RSpec also provides a default subject. For example:

RSpec.describe Array do
  it "starts empty" do
    expect(subject).to be_empty
  end
end

When the described class is an Array, RSpec’s implicit subject is a new instance of that class. You can also explicitly use: subject { described_class.new }

described_class refers to the class being tested.

Best practice: Prefer named subjects when they improve readability, especially in model specs.

3. before(:each) vs before(:all)

This is particularly important when working with database records.

HookExecutionState
before(:each)Before every exampleIsolated per example
before(:all)Once before the example groupShared across examples

before without arguments is equivalent to before(:each).

Example: before each

before(:each) do
  puts "Before each example"
end

Suppose there are three examples. Output:

Before each example
Example 1

Before each example
Example 2

Before each example
Example 3

Example: before all

before(:all) do
  puts "Before all examples"
end

Output:

Before all examples

Example 1
Example 2
Example 3

Important: Be careful with before(:all) and ActiveRecord

This is something I want you to remember for Rails development. RSpec Rails normally manages database transactions around individual examples. before(:all) runs outside that normal per-example transaction lifecycle. Consequently, database records created in before(:all) can leak between examples or require manual cleanup.

It can also result in shared mutable objects, making tests order-dependent.

My recommendation: For our Rails model and request specs, prefer let, let! and before(:each).

Use before(:all) only when you have a specific reason and understand its lifecycle implications.

Understand hook execution order

Suppose we have:

RSpec.describe "Outer" do
  before do
    puts "Outer before"
  end

  describe "Inner" do
    before do
      puts "Inner before"
    end

    it "runs example" do
      puts "Example"
    end
  end
end

What do you think the output will be?

It is: Outer before β†’ Inner before β†’ Example

The general rule is:

  • Parent group hooks run before nested group hooks.
  • Hooks registered within the same group run in declaration order.
  • let! internally registers a before hook at the point where it is declared, so declaration order can matter.

Practical assignment

Let’s combine what we’ve learned.

Let’s create another learning spec: touch spec/learning/rspec_lifecycle_spec.rb Implement the following exercises.

Exercise 1 – let!

Create an execution log. Define one let and one let!. Both should append different symbols to the execution log when evaluated.

Write an example verifying that:

  • The let! value is evaluated before the example.
  • The let value is not evaluated until referenced.

Exercise 2 – subject

Define a named subject called normalized_title. Its implementation should remove leading/trailing whitespace and convert a string to lowercase.

Verify that: " LEARN RAILS " produces: "learn rails"

Exercise 3 – Memoization

Access your named subject twice. Use an execution counter or log to verify that its block is evaluated only once within the same example.

Exercise 4 – Hook ordering

Create nested outer and inner example groups with before hooks. Predict and then verify the execution order. Run:

bundle exec rspec spec/learning/rspec_lifecycle_spec.rb --format documentation


RSpec.describe "Test rspec lifecycle hooks" do
  let(:execution_log) { [] }
  let(:title) { "  LEARN RSPEC  " }

  subject(:normalized_title) do
    execution_log << :subject_executed
    puts "subject execution_log: #{execution_log}"
    title.downcase.strip
  end

  let(:animal) do
    execution_log << :animal
    "Lion"
  end

  let!(:bird) do
    execution_log << :bird
    "Eagle"
  end

  describe "let and let!" do
    it "test let! evaluation" do
      expect(execution_log.count(:animal)).to eq(0)
      expect(execution_log.count(:bird)).to eq(1)
      expect(execution_log.count(:subject_executed)).to eq(0)
    end
  end

  describe "test subject lazyness" do
    it "call subject and check the counter" do
      normalized_title
      subject
      expect(execution_log.count(:subject_executed)).to eq(1)
    end
  end

  before do
    p "Outer hook"
  end

  describe "Test hook ordering" do
    before do
      p "Inner hook"
    end
    it "test inner hook" do
      expect(execution_log.count(:subject_executed)).to eq(0)
      expect(execution_log.count(:animal)).to eq(0)
      expect(execution_log.count(:bird)).to eq(1)
    end
  end
end

This is a good demonstration of eager versus lazy evaluation.

Remember this distinction:

LocationSyntax
Declarationsubject(:normalized_title) { ... }
Access inside examplenormalized_title
Access using default namesubject

A few observations before moving on:

  1. subject(:normalized_title) is lazy. It executes only when accessed.
  2. Calling normalized_title and then subject accesses the same memoized subject. The block executes only once per example.
  3. let!(:bird) executes automatically before each example, including examples in nested groups.
  4. let(:animal) never executes in your current examples because you don’t access it.

Rails 7+ API error handling that scales βš–️

A solid API error strategy gives you:

  • Consistent JSON error shapes
  • Correct HTTP status codes
  • Separation of concerns (domain vs transport)
  • Observability without leaking internals

Below is a practical, production-ready approach that covers controller hooks, controllers, models/libs, background jobs, and moreβ€”illustrated with a real scenario from Session::CouponCode.

Core principles

  • Keep transport (HTTP, JSON) in controllers; keep domain logic in models/libs.
  • Map known, expected failures to specific HTTP statuses.
  • Log unexpected failures; return a generic message to clients.
  • Centralize API error rendering in a base controller.

1) A single error boundary for all API controllers

Create a base Error::ApiError and rescue it (plus a safe catch‑all) in your ApiController.

# lib/error/api_error.rb
module Error
  class ApiError < StandardError
    attr_reader :status, :details
    def initialize(message, status = :unprocessable_entity, details: nil)
      super(message)
      @status  = status
      @details = details
    end
  end
end
# app/controllers/api_controller.rb
class ApiController < ActionController::Base
  include LocaleConcern
  skip_forgery_protection

  impersonates :user,
               ......

  # Specific handlers first
  rescue_from Error::ApiError,                          with: :handle_api_error
  rescue_from ActionController::ParameterMissing,       with: :handle_bad_request
  rescue_from ActiveRecord::RecordNotFound,             with: :handle_not_found
  rescue_from ActiveRecord::RecordInvalid,              with: :handle_unprocessable
  rescue_from ActiveRecord::RecordNotUnique,            with: :handle_conflict

  # Catch‑all last
  rescue_from StandardError,                            with: :handle_standard_error

  private

  def handle_api_error(e)
    render json: { success: false, error: e.message, details: e.details }, status: e.status
  end

  def handle_bad_request(e)
    render json: { success: false, error: e.message }, status: :bad_request
  end

  def handle_not_found(_e)
    render json: { success: false, error: 'Not found' }, status: :not_found
  end

  def handle_unprocessable(e)
    render json: { success: false, error: e.record.errors.full_messages }, status: :unprocessable_entity
  end

  def handle_conflict(_e)
    render json: { success: false, error: 'Conflict' }, status: :conflict
  end

  def handle_standard_error(e)
    Rollbar.error(e, path: request.fullpath, client_id: try(:current_client)&.id)
    render json: { success: false, error: 'Something went wrong' }, status: :internal_server_error
  end
end
  • Order matters. Specific rescue_from before StandardError.
  • This pattern avoids duplicating rescue_from across controllers and keeps HTML controllers unaffected.

2) Errors in before actions

Because before_action runs inside controllers, the same rescue_from handlers apply.

Two patterns:

  • Render in the hook for simple guard clauses:
before_action :require_current_client

def require_current_client
  return if current_client
  render json: { success: false, error: 'require_login' }, status: :unauthorized
end
  • Raise a domain/auth error and let rescue_from handle JSON:
# lib/error/unauthorized_error.rb
module Error
  class UnauthorizedError < Error::ApiError
    def initialize(message = 'require_login') = super(message, :unauthorized)
  end
end

before_action :require_current_client

def require_current_client
  raise Error::UnauthorizedError unless current_client
end

Prefer raising if you want consistent global handling and logging.

3) Errors inside controllers

Use explicit renders for happy-path control flow; raise for domain failures:

def create
  form = CreateThingForm.new(params.require(:thing).permit(:name))
  result = CreateThing.new(form: form).call

  if result.success?
    render json: { success: true, thing: result.thing }, status: :created
  else
    # Known domain failure β†’ raise an ApiError to map to 422
    raise Error::ApiError.new(result.message, :unprocessable_entity, details: result.details)
  end
end

Common controller exceptions (auto-mapped above):

  • ActionController::ParameterMissing β†’ 400
  • ActiveRecord::RecordNotFound β†’ 404
  • ActiveRecord::RecordInvalid β†’ 422
  • ActiveRecord::RecordNotUnique β†’ 409

4) Errors in models, services, and libs

Do not call render here. Either:

  • Return a result object (Success/Failure), or
  • Raise a domain‑specific exception that the controller maps to an HTTP response.

Example from our scenario, Session::CouponCode:

# lib/error/session/coupon_code_error.rb
module Error
  module Session
    class CouponCodeError < Error::ApiError; end
  end
end
# lib/session/coupon_code.rb
class Session::CouponCode
  def discount_dollars
    # ...
    case
    when coupon_code.gift_card?
      # ...
    when coupon_code.discount_code?
      # ...
    when coupon_code.multiorder_discount_code?
      # ...
    else
      raise Error::Session::CouponCodeError, 'Unrecognized discount code'
    end
  end
end

Then, in ApiController, the specific handler (or the Error::ApiError handler) renders JSON with a 422.

This preserves separation: models/libs raise; controllers decide HTTP.

5) Other important surfaces

  • ActiveJob / Sidekiq
  • Prefer retry_on, discard_on, and job‑level rescue with logging.
  • Return no HTTP here; jobs are async.
class MyJob < ApplicationJob
  retry_on Net::OpenTimeout, wait: 10.seconds, attempts: 3
  discard_on Error::ApiError
  rescue_from(StandardError) { |e| Rollbar.error(e) }
end
  • Mailers
  • Use rescue_from to avoid bubble‑ups crashing deliveries:
class ApplicationMailer < ActionMailer::Base
  rescue_from Postmark::InactiveRecipientError, Postmark::InvalidEmailRequestError do
    # no-op / log
  end
end
  • Routing / 404
  • For APIs, keep 404 mapping at the controller boundary with rescue_from ActiveRecord::RecordNotFound.
  • For HTML, config.exceptions_app = routes + ErrorsController.
  • Middleware / Rack
  • For truly global concerns, use middleware. This is rarely necessary for controller-scoped API errors in Rails.
  • Validation vs. Exceptions
  • Use validations (ActiveModel/ActiveRecord) for expected user errors.
  • Raise exceptions for exceptional conditions (invariants violated, external systems fail unexpectedly).

6) Observability

  • Always log unexpected errors in the catch‑all (StandardError).
  • Add minimal context: client_id, request.fullpath, feature flags.
  • Avoid leaking stack traces or internal messages to clients. Send generic messages on 500s.

7) Testing

  • Unit test domain services to ensure they raise Error::ApiError (or return Failure).
  • Controller/request specs: assert status codes and JSON shapes for both happy path and error path.
  • Ensure before_action guards either render or raise as intended.

Applying this to our scenario

  • /lib/session/coupon_code.rb raises Error::Session::CouponCodeError on unknown/invalid discount values.
  • /app/controllers/api_controller.rb rescues that error and returns JSON:
  • { success: false, error: e.message } with a 422 (or via Error::ApiError base).

This converts prior 500s into clean API responses and keeps error handling centralized.

When to generalize vs. specialize

  • Keep a catch‑all rescue_from StandardError in ApiController to prevent 500s from leaking internals.
  • Still add specific handlers (or subclass Error::ApiError) for known cases to control the correct status code and message.
  • Do not replace everything with only StandardErrorβ€”you’ll lose semantics and proper HTTP codes.

β€”

  • Key takeaways
  • Centralize API‐wide error handling in ApiController using specific handlers + a safe catch‑all.
  • Raise domain errors in models/libs; render JSON only in controllers.
  • Map common Rails exceptions to correct HTTP statuses; log unexpected errors.
  • Prefer Error::ApiError as a base for consistent message/status handling across the API.

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

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.