security

JWT And API Token Security

Core Controls

  • Use short expiry times and validate issuer, audience, signature algorithm, and time claims.
  • Never place secrets or unnecessary personal data in a JWT payload.
  • Store opaque API tokens hashed when the server only needs to verify them.
  • Plan revocation for logout, compromised credentials, and role changes.
  • Send bearer tokens only over HTTPS and avoid logging them.

Opaque Tokens Are Often Simpler

If the same application issues and verifies a token, an opaque random token can be easier to revoke and reason about.

PHP example
<?php

declare(strict_types=1);

$token = bin2hex(random_bytes(32));
$storedDigest = hash('sha256', $token);

echo strlen($token) . PHP_EOL;
echo strlen($storedDigest) . PHP_EOL;

// Prints:
// 64
// 64

Store the digest rather than the raw token when the server only needs to compare a presented credential. Show the raw token once to the client, just as you would with a password-reset token.

JWT Verification Is More Than Decoding

A JWT payload is base64url-encoded, not encrypted. Anyone holding the token can often read its claims.

Use a maintained library and configure it narrowly. Verify the signature with the expected algorithm and key. Check expiry, not-before time where used, issuer, audience, and any application-specific claims. Do not trust the token because it parses successfully.

Revocation And Rotation

Decide what happens when a token leaks, a user logs out, a staff member leaves, or permissions change. Short-lived access tokens reduce exposure. Refresh tokens, API keys, and signing keys need rotation and revocation plans.

Keep tokens out of URLs because URLs appear in histories, logs, analytics, and referrer headers. Redact authorization headers in logs and monitoring tools.

In Application Work

JWT libraries should be configured narrowly. For each API, decide whether JWTs provide a real benefit over simpler opaque credentials.

What To Check

Before moving on, make sure you can explain bearer-token risk, compare opaque tokens with JWTs, describe complete JWT verification, and plan expiry, revocation, rotation, transport, and logging controls.

Practice

Practice: Review An API Token Flow

Requirements

  • Define token lifetime and revocation behaviour.
  • Validate issuer, audience, algorithm, and expiry.
  • Keep bearer tokens out of URLs and logs.
  • Explain whether an opaque token would be simpler.
Show solution

Review Points

  • Use short expiry times and validate issuer, audience, signature algorithm, and time claims.
  • Never place secrets or unnecessary personal data in a JWT payload.
  • Store opaque API tokens hashed when the server only needs to verify them.
  • Plan revocation for logout, compromised credentials, and role changes.
  • Send bearer tokens only over HTTPS and avoid logging them.