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:
| Scenario | Expected result |
|---|---|
| Valid registration | 201 Created |
| Duplicate email | 422 Unprocessable Entity |
| Missing email | 422 Unprocessable Entity |
| Missing password | 422 Unprocessable Entity |
| Malicious mass-assignment attributes | Protected 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:
| Feature | Benefit |
|---|---|
| Explicit fields | Control exactly what the API exposes |
| Views | Different response representations for different use cases |
| Associations | Serialize related objects |
| Conditional fields | Include fields based on conditions |
| Renaming | Customize JSON attribute names |
| Collection rendering | Serialize 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:
- Strong adoption relative to the alternatives.
- Explicit field definitions, views and association support.
- 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:
| Method | Returns |
|---|---|
render | JSON string |
render_as_hash | Ruby Hash |
render_as_json | JSONified 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
| Concern | Selected tool |
| Serialization | Blueprinter |
| API specification | OpenAPI 3.2 |
| Documentation generation | rspec-openapi |
| Documentation UI | Swagger UI |
| Backend testing | RSpec |
| Test data | FactoryBot |
| Authentication | JWT + 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:
- Complete registration API and its request specs.
- Implement login, JWT response and refresh-token cookie.
- Add authenticated Task CRUD endpoints.
- Introduce rspec-openapi and generate our first OpenAPI document.
- Configure Swagger UI.
- Update documentation whenever request contracts change.
- 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:
| Scenario | Expected behaviour |
|---|---|
| Valid email and password | 200 OK |
| Incorrect password | 401 |
| Non-existent email | 401 |
| Missing email | 401 |
| Missing password | 401 |
| Invalid credentials response | Same generic error |
| Successful login | Returns valid JWT |
| JWT payload | Correct User ID |
| Response serialization | No 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:5173Rails: 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: truepermits 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:
authenticate_request!in ApplicationController.- Extract the Bearer token.
- Call
TokenVerifier. - Find and set
current_user. - Protect Task endpoints.
- Scope every query through
current_user.tasks. - 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.
















