Decoding a JSON Web Token (JWT) and verifying a JWT are two completely different operations—confusing them in backend middleware creates a critical authentication bypass vulnerability.

Decoding vs. Verifying a JWT: Critical Security Distinction

Decoding simply Base64URL-decodes the header and payload segments so a human or client UI can read claims like sub and exp. Anyone can forge a decoded payload. Verifying recalculates the cryptographic HMAC or RSA/ECDSA signature using a trusted server key and enforces algorithm, expiration (exp), and issuer (iss) constraints before trusting any claim.

To inspect a token during debugging without uploading credentials to a server, paste it into our client-side JWT Decoder or test HMAC signatures in the JWT Signer & Verifier.

1. How to Verify a JWT Safely in PHP 8.x (firebase/php-jwt)

Always pass an explicit Firebase\JWT\Key instance locking the expected algorithm—never read the algorithm dynamically from the untrusted token header:

<?php

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use UnexpectedValueException;

function authenticateBearerToken(string $authHeader, string $hmacSecret): array
{
    if (! preg_match('/^Bearer\s+([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/', $authHeader, $m)) {
        throw new UnexpectedValueException('Malformed Authorization Bearer header.');
    }

    // Explicitly pin HS256 so alg:none or RS256->HS256 confusion attacks are rejected
    $decoded = JWT::decode($m[1], new Key($hmacSecret, 'HS256'));

    if (($decoded->iss ?? '') !== 'https://auth.example.com') {
        throw new UnexpectedValueException('Unexpected token issuer.');
    }

    return (array) $decoded;
}

2. How to Verify an HS256 JWT in Node.js (Zero Dependencies, WebCrypto)

import crypto from 'node:crypto';

export function verifyJwtHs256(token, secret, expectedAud) {
  const parts = token.split('.');
  if (parts.length !== 3) throw new Error('Invalid JWT structure');

  const [headerB64, payloadB64, signatureB64] = parts;
  const header = JSON.parse(Buffer.from(headerB64, 'base64url').toString('utf8'));
  if (header.alg !== 'HS256') throw new Error(`Disallowed JWT alg: ${header.alg}`);

  const expectedSig = crypto
    .createHmac('sha256', secret)
    .update(`${headerB64}.${payloadB64}`)
    .digest('base64url');

  const a = Buffer.from(signatureB64);
  const b = Buffer.from(expectedSig);
  if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
    throw new Error('Invalid JWT signature');
  }

  const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString('utf8'));
  const nowSec = Math.floor(Date.now() / 1000);
  if (typeof payload.exp !== 'number' || payload.exp <= nowSec) {
    throw new Error('JWT has expired');
  }
  if (expectedAud && payload.aud !== expectedAud) {
    throw new Error('JWT audience mismatch');
  }
  return payload;
}

Stateless JWTs vs. Server-Side Sessions: When to Use Which

Requirement Short-Lived JWT + Refresh Token Server Session (Redis / MySQL)
Cross-service / microservice auth Ideal (verify locally via public key / JWKS) Requires shared session store lookup
Immediate single-user revocation Requires short TTL (5–15 min) or denylist Instant (DEL session:id)
Sensitive payload data Never store secrets in JWS payload (readable Base64URL) Stored server-side only

Common JWT Security Mistakes to Avoid

  • Weak HMAC secrets: An HS256 secret shorter than 32 random bytes (256 bits) can be brute-forced offline from a single captured token.
  • Storing long-lived JWTs in localStorage: Any XSS vulnerability can read localStorage. Prefer HttpOnly; Secure; SameSite=Lax cookies for browser web apps.

3. Asymmetric Signing (`RS256` / `ES256`) & JWKS Key Rotation in Microservices

While symmetric `HS256` works cleanly when a single PHP or Node.js monolith both issues and verifies tokens, sharing one HMAC secret across 12 downstream services means a compromise of *any* downstream service lets an attacker mint arbitrary admin tokens! Production multi-service architectures prefer **asymmetric ECDSA (`ES256`) or RSA (`RS256`)**:

  • Auth Server (Private Key): Signs tokens using an ECDSA P-256 private key (`ES256` produces compact 64-byte signatures vs 256-byte RSA-2048 signatures and verifies 3x faster!).
  • Downstream Resource APIs (Public Key / JWKS): Fetch and cache the Auth Server’s public `/.well-known/jwks.json` endpoint keyed by the JWT header’s `kid` (Key ID). Resource APIs can verify tokens offline in `< 0.1 ms` without holding any secret capable of signing new tokens.
<?php

use Firebase\JWT\CachedKeySet;
use Firebase\JWT\JWT;

// Verify RS256 / ES256 tokens against a cached remote JWKS endpoint (Auth0, Cognito, Keycloak, Google)
$keySet = new CachedKeySet(
    'https://auth.example.com/.well-known/jwks.json',
    $psr18HttpClient,
    $psr17RequestFactory,
    $psr6CachePool, // Caches public keys in Redis/APCu so every request doesn't hit HTTPS!
    3600,           // Cache TTL (seconds)
    true            // Rate-limit refreshes on unknown kid to prevent JWKS DoS
);

$claims = JWT::decode($bearerToken, $keySet);

4. Safe Refresh-Token Rotation & Theft Detection Pattern

Because a stolen JWT remains valid until its `exp` timestamp passes, keep access-token lifetimes short (`5–15 minutes`) and pair them with a rotating opaque **Refresh Token**:

  1. Generate a 32-byte CSPRNG opaque refresh token (`bin2hex(random_bytes(32))`), store only its `SHA-256` hash (Hash Generator) in MySQL/Redis alongside a `token_family_id`, and send it in an `HttpOnly; Secure; SameSite=Strict; Path=/auth/refresh` cookie.
  2. When `/auth/refresh` is called, atomically mark the old refresh token as `consumed_at = NOW()` and issue a fresh access JWT + a rotated refresh token in the same family.
  3. Automatic Replay Detection: If an already-consumed refresh token is ever presented a second time, either an attacker or the victim replayed a stolen token—immediately revoke the entire `token_family_id` and force re-authentication!

5. Clock Skew (`leeway`) and Standard RFC 7519 Claims Checklist

  • Allow 30–60 seconds of NTP clock leeway: Container clocks across cloud nodes can drift by a few seconds, causing freshly minted `nbf` (Not Before) or `iat` tokens to fail spuriously. Set `JWT::$leeway = 30;` in `firebase/php-jwt`.
  • Always check `aud` (Audience): Without an `aud` check, a valid JWT issued for your *Staging* or *Billing* service might be accepted by your *Admin* API if both trust the same identity provider!
  • Test API Authorization headers end-to-end: Verify `401 Unauthorized` vs `403 Forbidden` responses using our Online REST API Tester and HTTP Status Code Reference.