← All posts

Field notes / Security

When Decoding Becomes Trust: Reviewing JWT Authentication Middleware

Authentication bugs are rarely about whether an application has authentication.

More often, the interesting question is:

At what point does the application decide that an identity can be trusted, and what evidence justified that decision?

That distinction becomes especially important when reviewing JWT authentication middleware. A few lines of code can sit between attacker-controlled input and an application-wide assumption that req.user represents a legitimate authenticated user.

If those lines get the trust decision wrong, every protected route downstream may inherit the mistake.

Authentication Is More Than Logging In

It is easy to mentally associate authentication with the login screen:

Username + Password
        ↓
    POST /login
        ↓
Credentials validated
        ↓
   JWT issued

But authentication does not end there.

After login, the client sends the credential with subsequent requests:

GET /account
Authorization: Bearer eyJhbGciOi...

Authentication middleware must make another security decision:

Request
   ↓
Credential present?
   ↓
Credential authentic?
   ↓
Credential still valid?
   ↓
Issued by someone we trust?
   ↓
Intended for this application?
   ↓
Which identity does it represent?
   ↓
req.user

Only after those questions have trustworthy answers should authorization begin deciding what that identity is allowed to do.

That gives us a useful security contract:

Before an application treats a request as authenticated, the credential must be genuine, valid, unexpired, issued by a trusted authority, intended for the application, and securely associated with a legitimate identity.

The important word is trusted.

A JWT containing "sub": "1842" does not prove that user 1842 made the request.

It is merely a claim until the application proves otherwise.

Start With Attacker-Controlled Input

Consider middleware beginning with:

const authHeader = req.headers.authorization;

That value came from the request.

Therefore, the attacker controls it.

They control whether the header exists, its format, the token string, and potentially every claim inside that token.

This is where an effective security review begins.

Instead of immediately asking whether the code looks correct, trace the data:

Where does attacker-controlled input enter?
                ↓
What assumptions does the application make about it?
                ↓
Where does the application begin trusting it?
                ↓
Was that trust justified?

Those four questions apply far beyond JWTs. They work for cookies, API keys, object identifiers, request parameters, authorization headers, and many other application security reviews.

Decoding a JWT Is Not Verifying It

Now consider this line:

const decoded = jwt.decode(token);

It looks reasonable.

There is a token. The application decodes it. Claims appear. The application continues.

But parsing data and authenticating data are completely different operations.

decode() can extract the contents of a JWT. It does not establish that the token came from a trusted issuer or that its contents have not been modified.

That distinction is critical.

Suppose an attacker supplies a token containing claims equivalent to:

{
  "sub": "1842",
  "role": "admin",
  "exp": 9999999999
}

If the application merely decodes those values, it has learned what the attacker claims.

It has not established that any of those claims are true.

A useful mental model is:

decode()
    ↓
"What does this token say?"

verify()
    ↓
"Do I have cryptographic evidence that I should trust what this token says?"

Confusing those questions can produce a complete authentication bypass.

And it is an understandable implementation mistake. Functions such as decode() and verify() can sit next to each other in the same JWT library while having dramatically different security consequences.

Small implementation difference. Large trust-boundary difference.

RS256 and the Source of Trust

With RS256, JWT signing uses asymmetric cryptography.

The issuer possesses a private key and signs tokens with it. Services validating those tokens use the corresponding public key.

Conceptually:

Identity Provider
   Private Key
       ↓
   Signs JWT
       ↓
      JWT
       ↓
      API
   Public Key
       ↓
Verify Signature

A downstream API can verify that a token was signed by the expected authority without possessing the private key required to create new legitimate tokens.

That separation is especially useful when authentication crosses service trust boundaries.

But RS256 only helps if the application actually performs the verification.

Using RS256 while calling only decode() is a little like installing a deadbolt and then checking whether someone brought something shaped like a key.

The cryptographic trust mechanism exists, but the application never asks it to prove anything.

Follow the Claim Until It Becomes Identity

Suppose the middleware continues with:

const user = await db.users.findById(decoded.sub);

This is where the security review becomes more interesting.

decoded.sub originated in attacker-controlled input.

Without signature verification, the application has no trustworthy evidence that the subject claim is legitimate.

Yet the application now uses it to select a user from the database.

The trust transition looks like this:

Attacker-controlled JWT
        ↓
     decode()
        ↓
decoded.sub
        ↓
db.users.findById(decoded.sub)
        ↓
     user record
        ↓
req.user = user

The database lookup does not make the original claim trustworthy.

Finding a real user with that identifier only proves that the user exists.

It does not prove that the requester is that user.

The application begins trusting the unverified identity when it uses decoded.sub to retrieve the user record. It formalizes that trust when it assigns the resulting record to:

req.user = user;

At that point, attacker-controlled data has crossed the authentication trust boundary and become application state.

Everything downstream may now reasonably assume:

req.user = authenticated identity

Except authentication never actually occurred.

From Trust Failure to Impersonation

Once that data flow is understood, the exploit path becomes straightforward:

Attacker creates JWT
        ↓
sub = victim's user ID
        ↓
Application decodes token
        ↓
No signature verification
        ↓
decoded.sub = victim
        ↓
Database retrieves victim
        ↓
req.user = victim

The attacker does not need the victim's password.

They do not need the legitimate JWT.

They need only an identifier that causes the application to retrieve the victim's record.

This is why the finding is not simply:

The application uses decode() instead of verify().

That describes the coding mistake.

The security finding is:

Authentication bypass through unverified JWT claims allows an attacker to impersonate another user.

The distinction matters.

Good AppSec reviews connect implementation defects to security consequences.

Signature Verification Is Only Part of JWT Validation

Fixing signature verification is essential, but a valid signature alone does not necessarily mean a token should be accepted.

Consider a legitimate JWT containing:

{
  "sub": "1842",
  "iss": "accounts.example.test",
  "aud": "customer-api",
  "exp": 1784134800
}

Several separate questions still exist:

Signature: Was the token cryptographically signed by a trusted key?

Issuer (iss): Did it come from the identity system this application trusts?

Audience (aud): Was the token actually issued for this API?

Expiration (exp): Is the credential still within its permitted lifetime?

Subject (sub): Does the claimed identity map to an existing and appropriate user?

A robust validation path therefore resembles:

JWT received
    ↓
Verify signature
    ↓
Validate issuer
    ↓
Validate audience
    ↓
Validate lifetime
    ↓
Resolve subject
    ↓
Check user status if required
    ↓
Establish req.user

Every step answers a different trust question.

Authentication and Authorization Are Independent

Correct authentication does not guarantee correct authorization.

Suppose authentication works perfectly and establishes:

req.user.id = 1842

Now consider:

GET /account/7331

and application logic resembling:

const requestedUserId = req.params.userId;

const account =
    await db.accounts.findByUserId(requestedUserId);

The application knows who made the request.

But it never asks whether that user is allowed to access the requested account.

That creates a second, independent security problem:

Authenticated as 1842
        ↓
Request /account/7331
        ↓
Application retrieves 7331
        ↓
No ownership/authorization check
        ↓
Account returned

This is broken object-level authorization, commonly called BOLA.

The authentication vulnerability and the authorization vulnerability should not be collapsed into one finding.

Either may be exploitable independently.

That means a security review could legitimately identify two separate blockers:

Authentication failure
        +
Object authorization failure

Fixing one does not repair the other.

Tiny Time Bugs Can Break Security Logic Too

JWT expiration handling contains another easy trap.

JWT timestamps such as exp are conventionally represented in seconds since the Unix epoch.

JavaScript's:

Date.now()

returns milliseconds.

So code such as:

if (decoded.exp && decoded.exp < Date.now()) {

compares values expressed in different units.

This is primarily a correctness problem, but authentication correctness is security-relevant when the broken logic controls credential acceptance.

More importantly, expiration validation cannot compensate for missing signature verification.

If an attacker controls the unsigned exp claim, they can simply choose another value.

Before trusting a claim, first establish that the attacker cannot arbitrarily modify it.

Active Users and Token Revocation Require Context

Some authentication requirements cannot be classified correctly without understanding the system's intended behavior.

For example, retrieving a user record may prove the user exists, but perhaps disabled users must immediately lose access.

That could require:

user exists
    +
user is active

Similarly, JWTs are often valid until expiration. Some environments require immediate invalidation after account disablement, credential compromise, logout, or another security event.

Instead of automatically filing:

Missing token revocation.

A stronger security review asks:

Is immediate token invalidation a security requirement for this system? If disabled users or compromised credentials must lose access before token expiration, the authentication design requires a revocation, introspection, or equivalent invalidation mechanism.

That distinction separates demonstrated vulnerabilities from architectural questions requiring additional context.

Security Review Comments Should Teach

A security review is not improved by making developers feel stupid.

JWT libraries make decode() versus verify() an easy mistake to make. A useful review explains both the defect and its consequence.

For example:

Requesting changes. The middleware decodes the JWT without verifying its signature, allowing attacker-controlled claims such as sub to become authenticated identity. Use cryptographic verification and validate the expected issuer and audience before resolving the user.

Then separately address authorization:

/account/:userId retrieves the requested account without verifying that the authenticated user is authorized to access that object. Add an ownership or equivalent authorization check before returning the account.

Good review comments answer three questions:

What is wrong?
Why does it matter?
What needs to change?

No security theater required.

Tests Should Attack the Trust Contract

A corrected implementation should not merely look secure.

Its tests should prove that the security contract fails safely.

Useful negative tests include:

The important question is not simply:

Does a legitimate token work?

It is:

Can the test suite prove that illegitimate credentials and unauthorized requests fail?

If the tests cannot fail on a forged token, the security fix is asserted rather than demonstrated.

The Bigger AppSec Pattern

JWT middleware is one example of a much broader pattern.

Applications constantly transform untrusted input into trusted state:

Request parameter → database query
Cookie → session
JWT claim → identity
Role claim → privilege
Object ID → resource
Webhook → business action
API response → application decision

The review technique remains remarkably consistent:

1. Identify attacker-controlled input.

2. Follow it through the application.

3. Identify assumptions made about it.

4. Locate the exact trust boundary.

5. Determine what evidence justifies crossing that boundary.

6. Trace what an attacker gains if the assumption is false.

This shifts code review away from hunting for suspicious functions and toward understanding how the application constructs trust.

That is the more transferable skill.

The Question Behind the Code

The dangerous line in vulnerable authentication middleware is not necessarily the line that parses the JWT.

It may be the line several operations later where the application finally says:

req.user = user;

By then, a series of assumptions have already been made.

Where did the identity originate?

Was the credential authentic?

Who issued it?

Was it intended for this service?

Could the attacker modify its claims?

Does the identity still have access?

And once identity has been established, is that identity actually authorized to access the requested object?

The goal of AppSec review is not merely to spot decode() where verify() should have been used.

It is to recognize the moment an application converts something an attacker can say into something the application believes.

That moment is the trust boundary.

And that is where some of the most consequential security bugs live.

← Back to the blog