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.
| Claim | Meaning | Our usage |
|---|---|---|
sub | Subject | User ID |
iss | Issuer | Our Rails API |
aud | Audience | Our React application |
iat | Issued at | Token creation time |
exp | Expiration | Token expiry |
jti | JWT ID | Unique 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.
| Algorithm | Description |
|---|---|
| HS256 | HMAC using SHA-256 and a shared secret |
| RS256 | RSA with SHA-256, using private/public keys |
| ES256 | ECDSA 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.
| Component | Responsibility |
|---|---|
AccessToken | Generate signed JWT |
TokenVerifier | Decode and verify JWT |
AuthenticationController | Login, logout and refresh HTTP endpoints |
RefreshTokenService | Generate, rotate and revoke refresh tokens |
RefreshSession | Persist 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:
payloadis now a class method. Subclasses inherit it.signing_secretis 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) TOJWT.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:
payloadwas an instance method.sendbypasses 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:
| Check | What are we protecting against? |
|---|---|
| Signature | Token modification or forged token |
| Algorithm | Algorithm 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 claims | Missing 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:
| Argument | Meaning |
|---|---|
token | Incoming JWT string |
secret | Signing secret |
true | Enable signature verification |
options | Algorithm 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:
| Input | Result |
|---|---|
| Valid JWT | Verified payload Hash |
| Expired JWT | nil |
| Invalid signature | nil |
| Invalid issuer | nil |
| Invalid audience | nil |
| Malformed JWT | nil |
| Missing token | nil |
Why return the payload instead of the User object? Because these are separate responsibilities:
TokenVerifierverifies 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::ALGORITHMas the fixed algorithm.Base::ISSUERas the expected issuer.Base::AUDIENCEas 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.
| Test | Expected result |
|---|---|
| Valid JWT generated by AccessToken | Returns Hash |
| Correct subject | sub matches User ID |
| Expired token | Returns nil |
| Wrong signing secret | Returns nil |
| Wrong issuer | Returns nil |
| Wrong audience | Returns nil |
| Malformed token / nil token | Returns 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?
| Code | Responsibility |
|---|---|
token.is_a?(String) | Reject unexpected input types |
signing_secret | Reuse secret validation from Base |
algorithm | Only accept HS256 |
verify_iss | Validate trusted issuer |
verify_aud | Validate intended audience |
verify_expiration | Reject expired tokens |
verify_iat | Reject invalid/future issuance times |
verify_jti | Verify JWT ID |
required_claims | Reject missing claims |
valid_subject? | Ensure a valid user identifier |
valid_jti? | Ensure a non-empty token identifier |
rescue JWT::TokenError | Convert 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.






