JWT Authentication Explained: Create, Verify, Refresh, and Debug Access Tokens Safely
jwtauthenticationapissecurityjavascriptpython

JWT Authentication Explained: Create, Verify, Refresh, and Debug Access Tokens Safely

TThe Code Website Editorial Team
2026-12-05
7 min read

Learn how to create, verify, refresh, store, and troubleshoot JWT access tokens with practical JavaScript and Python guidance.

JWT authentication is straightforward to demonstrate but easy to weaken in production. This guide explains how JSON Web Tokens work, how to create and verify access tokens, how refresh-token rotation fits into the flow, and which security checks to monitor when debugging an API.

Overview

A JSON Web Token (JWT) is a compact, signed representation of claims. An API can use it to identify a caller without storing every access-token session in a central database. A JWT normally has three Base64URL-encoded parts separated by periods:

  1. Header: identifies the token type and signing algorithm.
  2. Payload: contains claims such as the subject, issuer, audience, and expiration time.
  3. Signature: proves that the signed header and payload have not been altered.

The payload is encoded, not encrypted. Anyone who obtains a token can usually decode its header and claims, so do not place passwords, private keys, payment details, or other sensitive values inside it. A JWT decoder is useful for inspecting a token during development, but decoding alone does not verify authenticity.

A practical authentication flow separates short-lived access tokens from longer-lived refresh tokens. The client sends the access token to a protected API, commonly in an Authorization: Bearer header. When the access token expires, the client presents the refresh token to a dedicated endpoint. The server validates the refresh token and issues a new access token. In a stronger design, refresh tokens are rotated and the previous token is invalidated after use.

JWT authentication is not the same as OAuth or OpenID Connect. OAuth describes delegated authorization, while OpenID Connect adds an identity layer on top of OAuth. JWT is a token format that may be used within those systems or in a custom API authentication flow. Use a mature identity provider or framework integration when your application needs federation, social login, consent, or centralized account management.

What to track

Token claims and validation rules

Define the claims your API actually needs and validate important claims on every protected request. Common claims include:

  • sub: the stable identifier of the user or service.
  • iss: the trusted issuer that created the token.
  • aud: the API or service intended to receive it.
  • exp: the expiration time, expressed as a NumericDate.
  • nbf: the time before which the token must not be accepted.
  • iat: the time at which the token was issued.
  • jti: an optional unique identifier useful for replay detection or revocation records.

Do not treat a decoded sub value as trusted until signature, issuer, audience, time, and algorithm checks have passed. Also validate authorization separately: a valid token proves that the token was issued and is acceptable for the API, but it does not automatically grant every operation.

Algorithm, key, and issuer configuration

ChoiceTypical useOperational consideration
HS256 or another HMAC algorithmSmall, controlled systems with one trusted signing serviceThe same secret signs and verifies tokens, so it must be shared carefully and protected across all verifiers.
RS256 or another RSA algorithmOne issuer signing for multiple servicesThe issuer keeps a private key while verifiers can use a public key.
ES256 or another elliptic-curve algorithmSystems that standardize on elliptic-curve keysKey handling and library support must be tested consistently across languages.

Choose an allowed algorithm in server configuration and pass that allowlist to the verification library. Never accept whichever algorithm the incoming header requests. Keep key identifiers such as kid tied to a trusted key set, and plan how signing keys will rotate without immediately invalidating every legitimate access token.

JavaScript verification example

The following example uses the jose package and an HMAC secret supplied through configuration. It explicitly restricts the algorithm and checks the issuer and audience.

import { jwtVerify } from 'jose';

const secret = new TextEncoder().encode(process.env.JWT_SECRET);

export async function verifyAccessToken(token) {
  const result = await jwtVerify(token, secret, {
    algorithms: ['HS256'],
    issuer: 'https://auth.example.test',
    audience: 'orders-api'
  });

  return result.payload;
}

// In a route handler:
try {
  const token = request.headers.get('authorization')?.replace(/^Bearer\\s+/i, '');
  if (!token) throw new Error('missing token');
  const claims = await verifyAccessToken(token);
  // Check claims and resource permissions before continuing.
} catch {
  // Return an authentication failure without exposing verification details.
}

Use the library's normal error types and logging facilities in a real application. Return a generic client-facing error while recording enough server-side context to distinguish an expired token from a malformed token or a configuration failure.

Python verification example

With a library such as PyJWT, keep the allowed algorithm and expected claims explicit. The exact import and exception handling should follow the version you install and your framework's conventions.

import os
import jwt
from jwt import ExpiredSignatureError, InvalidTokenError

SECRET = os.environ['JWT_SECRET']


def verify_access_token(token: str) -> dict:
    return jwt.decode(
        token,
        SECRET,
        algorithms=['HS256'],
        issuer='https://auth.example.test',
        audience='orders-api',
        options={'require': ['exp', 'sub', 'iss', 'aud']},
    )

try:
    claims = verify_access_token(token_from_request)
except ExpiredSignatureError:
    # Ask the client to obtain a new access token.
    raise AuthenticationError('access token expired')
except InvalidTokenError:
    raise AuthenticationError('invalid access token')

Storage and transport

Use HTTPS for every token exchange and protected request. For browser applications, avoid casually placing long-lived refresh tokens in JavaScript-readable storage: a script-injection vulnerability can expose them. A common design is an HttpOnly, Secure cookie with an appropriate SameSite setting, combined with CSRF defenses where cross-site requests are possible. Short-lived access tokens may be held in memory, depending on the application's architecture. For native applications, use the platform's secure credential storage rather than a plain file or general-purpose preference store.

Cadence and checkpoints

Authentication should be reviewed as a recurring operational concern, not only when a login feature is first shipped. A monthly or quarterly checkpoint is useful for small systems; higher-risk services may need a more frequent review.

At each review

  • Confirm that access tokens have an intentional lifetime and that expired tokens are rejected.
  • Check signing-key age, storage, rotation procedures, and the behavior of multiple active keys during a transition.
  • Review refresh-token rotation, reuse detection, revocation, and logout behavior.
  • Verify that issuer, audience, algorithm, and required-claim checks are covered by automated tests.
  • Inspect authentication failure logs for unusual spikes without logging complete tokens or secrets.
  • Test protected routes for both authentication and authorization; a valid user token should not bypass ownership or role checks.
  • Review dependency updates in the JWT, web framework, cookie, and identity-provider integrations.

When a service has several APIs, document which issuer and audience each API accepts. This prevents a token intended for one service from being treated as a credential for another. If your team uses a JSON formatter or online JWT decoder while debugging, remove real credentials first and use a fabricated token whenever possible.

How to interpret changes

A rising number of 401 Unauthorized responses can indicate expired access tokens, clock skew, a changed issuer, a missing bearer prefix, or a failed key rotation. A rising number of 403 Forbidden responses usually points to an authorization decision after authentication succeeded. Compare these patterns with deployment times and identity-provider events rather than immediately increasing token lifetimes. For a broader response-code workflow, see the HTTP status codes and API errors reference.

For an “invalid signature” error, check that the verifier is using the correct key, algorithm, and key version. Confirm that the token was not copied with extra whitespace or altered during transport. If asymmetric signing is involved, verify that the public key set is current and that the kid maps to the expected key.

For an “expired token” error, inspect server clocks and the token's exp value. A small, deliberate clock-skew tolerance may be appropriate, but it should not replace synchronized system clocks or sensible token lifetimes. For malformed-token errors, verify that the client sends only the token after the Bearer scheme. The JavaScript Fetch API guide can help trace how headers and API errors move through a frontend client.

Do not “fix” repeated authentication failures by decoding tokens without verification, accepting every algorithm, or placing sensitive data in claims. Those changes hide the symptom while weakening the trust boundary.

When to revisit

Revisit this guide whenever you add a protected route, introduce a new client, change an identity provider, rotate signing keys, alter cookie settings, or change access and refresh-token lifetimes. Also review the implementation after a security incident, a major framework update, or a change from a single API to several services.

Use this short implementation checklist before release:

  1. Choose a supported signing algorithm and enforce it during verification.
  2. Keep signing secrets and private keys outside source control and application responses.
  3. Validate the signature, issuer, audience, expiration, not-before time, and required claims.
  4. Keep access tokens short-lived and design refresh-token rotation and revocation deliberately.
  5. Protect browser tokens with an appropriate storage and transport strategy.
  6. Separate authentication from resource authorization.
  7. Test expired, malformed, wrong-audience, wrong-issuer, altered, and replayed tokens.
  8. Monitor failures without storing complete bearer tokens in logs.

JWT authentication works best when treated as a set of explicit, testable policies rather than a single token-parsing function. Record those policies in your API documentation, review them on a regular cadence, and update the checklist whenever the surrounding identity or deployment architecture changes.

Related Topics

#jwt#authentication#apis#security#javascript#python
T

The Code Website Editorial Team

Developer Resources Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.