JWT Authentication for Mobile & Web Apps: The Complete Guide

JWT (JSON Web Token) is the de facto standard for stateless authentication in mobile and web apps. It’s also one of the most commonly misimplemented pieces of a backend — small mistakes in how tokens are issued, stored, or validated turn into real security holes. This guide covers how JWTs actually work and how to implement them correctly.

What’s Actually Inside a JWT

A JWT is three Base64URL-encoded parts joined by dots: header.payload.signature. The header names the signing algorithm; the payload holds claims (user ID, expiry, issuer, any custom data you add); the signature is computed over the header and payload so the server can detect tampering. Critically: the payload is encoded, not encrypted — anyone can decode and read it. Never put passwords, secrets, or sensitive personal data in a JWT payload.

Access Tokens vs Refresh Tokens

Don’t issue one long-lived token. Use two:

  • Access token: short-lived (5-15 minutes), sent with every API request, used to authorize the actual action. Because it’s short-lived, a leaked access token is a small, time-limited risk.
  • Refresh token: long-lived (days to weeks), used only to get a new access token when the old one expires. Stored more securely and sent far less often, which limits its exposure.

When a refresh token is used, issue a brand-new refresh token too and invalidate the old one (refresh token rotation). This means a stolen refresh token only works once — if the real user’s app tries to use the now-invalidated one next, you know a token was compromised and can revoke the whole session.

Issuing a Token (PHP example)

use FirebaseJWTJWT;

$payload = [
    'iss' => 'https://api.techstackgame.com',
    'sub' => $userId,
    'iat' => time(),
    'exp' => time() + 900, // 15 minutes
];

$accessToken = JWT::encode($payload, $_ENV['JWT_SECRET'], 'HS256');

Always set exp. A JWT with no expiry is valid forever once issued, which defeats the point of using short-lived tokens at all.

Validating a Token

use FirebaseJWTJWT;
use FirebaseJWTKey;

try {
    $decoded = JWT::decode($token, new Key($_ENV['JWT_SECRET'], 'HS256'));
    $userId = $decoded->sub;
} catch (FirebaseJWTExpiredException $e) {
    respond(401, ['error' => 'Token expired']);
} catch (Exception $e) {
    respond(401, ['error' => 'Invalid token']);
}

Catch expiry and general validation failures separately — a client can automatically trigger a refresh-token flow on “expired,” but should force a full re-login on “invalid” (tampered/malformed).

The “alg: none” Attack and Why It Still Matters

Some JWT libraries historically accepted a token whose header claimed "alg": "none", skipping signature verification entirely — letting an attacker forge any payload they wanted. Modern libraries (like firebase/php-jwt used above) fix this by requiring you to explicitly pass the expected algorithm, as in the example. Never let the algorithm be read from the token itself — always pin it server-side to what you issued with.

Secure Storage on the Client

  • Android: use EncryptedSharedPreferences (part of Jetpack Security) or the Android Keystore — never plain SharedPreferences for tokens.
  • iOS: use Keychain Services — never UserDefaults, which is not encrypted at rest.
  • Web: an httpOnly, Secure cookie resists XSS token theft better than localStorage, which any injected script can read directly.

Revocation: The One Thing Stateless Tokens Can’t Do Natively

Because JWTs are stateless, a server can’t “delete” one once issued — it’s valid until it expires, full stop. For a logout or “sign out of all devices” feature, you need a small amount of state: keep a server-side table of active (or revoked) refresh-token IDs. Access tokens stay stateless and short-lived; refresh tokens get the minimal state needed for revocation to actually work.

Key Takeaways

  • JWT payloads are readable, not secret — never put sensitive data in one.
  • Use short-lived access tokens plus long-lived, rotating refresh tokens — never one long-lived token for everything.
  • Always set and check exp, and always pin the expected signing algorithm server-side.
  • Store tokens in platform-appropriate secure storage: Android Keystore, iOS Keychain, httpOnly cookies on web.
  • Keep a minimal server-side revocation list for refresh tokens so “log out everywhere” actually works.