Skip to content
Muhammet Şafak
tr
Web Development 4 min read

JWT Authentication: How It Works, When It Fits, and Common Pitfalls

A practical look at JWT authentication — token structure, signing mechanics, and the trade-offs you need to understand before reaching for it.

TL;DR

A JWT is a compact, signed token of the form header.payload.signature that lets a server verify a request without keeping session state. The price is that a token cannot be revoked before it expires, so JWT fits short-lived access best.

Three metal plates labelled header, payload and signature, with a violet lock bolt at the end

JWT has become the default authentication mechanism in modern web applications. That ubiquity is largely a good thing — but “default” doesn’t mean “always the right choice.” I covered the plainest form of authentication in the post on HTTP Basic Authentication; to see what JWT brings, it helps to look first at what Basic doesn’t. In this post I’ll explain how JWT works, when it earns its keep, and the mistakes I’ve seen repeatedly over the years.

What Is a JWT and What Problem Does It Solve?

JWT (JSON Web Token) is a token format for conveying verifiable information between two parties; RFC 7519: JSON Web Token (JWT), May 2015 defines it as “a compact, URL-safe means of representing claims to be transferred between two parties”. It consists of three sections separated by dots:

header.payload.signature

header declares the token type and the signing algorithm; payload carries the actual data; signature is the first two sections signed with a secret key. The signature lets a server verify that the token content hasn’t been tampered with — without the key ever travelling inside the token.

The core problem JWT solves is this: the server doesn’t need to keep session state on its end. The token validates itself. This eliminates the headache of sharing session state across multiple servers.

What you pay for it

That statelessness isn’t free. With a stateful session you can revoke a user instantly — delete the record and it’s done. With JWT, a token remains valid until it expires, no matter what you do. Revoking a compromised token is inherently hard; it’s baked into how JWT works.

That’s why I frame JWT this way: excellent for short-lived access; weak for scenarios where you need “I must be able to invalidate this session at any moment.”

You can patch this weakness with a blacklist — store revoked tokens somewhere and check every incoming request against that store. But be honest with yourself: at that point you’ve abandoned the original promise of JWT, which was “the server holds no session state.” The moment you add a blacklist, you give back some of the simplicity that statelessness offered. That’s not necessarily a bad decision — but it should be a conscious one.

In practice: signing and verification

To make this concrete, here’s a small class that does signing and verification by hand. Don’t write this yourself in production — use a battle-tested package like firebase/php-jwt. This is just to make the mechanism visible:

class JWT
{
    protected const ALGORITHM = 'HS256';
    protected const SIGNATURE_ALGORITHM = 'sha256';

    public static function encode(string $key, array $payload, ?int $ttl = null): string
    {
        $header = base64_encode(json_encode([
            'typ' => 'JWT',
            'alg' => self::ALGORITHM,
        ]));
        $payload = base64_encode(json_encode([
            'data'       => $payload,
            'created_at' => time(),
            'ttl'        => $ttl,
        ]));

        return $header . '.' . $payload . '.' . self::signature($key, $header, $payload);
    }

    public static function decode(string $key, string $jwt): array|false
    {
        try {
            [$h, $p, $signature] = explode('.', $jwt);
            if (!hash_equals(self::signature($key, $h, $p), $signature)) {
                return false;
            }
            $payload = json_decode(base64_decode($p), true);
            if ($payload['ttl'] !== null && time() - $payload['created_at'] > $payload['ttl']) {
                return false;
            }
            return $payload['data'];
        } catch (\Throwable) {
            return false;
        }
    }

    private static function signature(string $key, string $header, string $payload): string
    {
        return base64_encode(hash_hmac(self::SIGNATURE_ALGORITHM, $header . '.' . $payload, $key, true));
    }
}

A note on the class itself: it uses base64_encode(), but the JWS specification requires base64url, which RFC 7515: JSON Web Signature (JWS), May 2015 defines as Base64 with the URL- and filename-safe character set and all trailing = characters omitted. Its data, created_at and ttl members are also my own, not the registered claims of RFC 7519, so tokens from this class will not interoperate with standard JWT libraries.

One line here that shouldn’t go unnoticed: I compare signatures with hash_equals(), not ==. A plain equality check is vulnerable to timing attacks — an attacker can infer information from how long the comparison takes. It’s a small detail, but in security code there’s no such thing as a “small detail.”

Mistakes I’ve seen over the years

  • Long-lived access tokens. Access tokens should expire in 15 minutes to an hour. For persistent sessions, use a separate, longer-lived refresh token.
  • Storing tokens in the wrong place. Putting a token in localStorage exposes it to XSS. An HttpOnly + Secure cookie is significantly safer.
  • Putting sensitive data in the payload. The payload is signed but not encrypted — anyone who base64-decodes it can read it. Passwords, ID numbers, and similar sensitive values have no place there.
  • Forgetting the alg: none attack. If the verification side blindly reads the algorithm from the token itself, an attacker can bypass the signature entirely. Hard-code the expected algorithm in your code; never trust the token to tell you how to verify it. RFC 8725: JSON Web Token Best Current Practices, February 2020 says the same: libraries “MUST enable the caller to specify a supported set of algorithms and MUST NOT use any other algorithms when performing cryptographic operations”.

Summary

JWT is an elegant mechanism — but it isn’t magic. You pay for the scalability benefit of statelessness with the difficulty of revocation. If you keep tokens short-lived, store them in the right place, and verify signatures rigorously, the trade-off is reasonable for most applications. If you can’t meet those conditions, a classic server-side session is still a perfectly respectable choice — newer doesn’t always mean better.

Experiments on this topic

Why a Bluetooth proximity lock needs a proximity assessment, not a raw present/absent signal; it shipped as SignalLock for macOS, Windows and Linux.

What it does today

Locks the screen on macOS, Windows and Linux when the device you carry moves away; the call rests on a proximity assessment rather than a raw present/absent signal, so fluctuation no longer produces false locks. The menu bar and system tray app is published on all three platforms and ready to install.

Open-Source Desktop Rust Slint btleplug +1 more
March 2026 — May 2026

A proxy between an agent and its MCP servers: scans results for injection, masks PII, enforces access and logs decisions to a hash-chained audit log.

What it does today

Sits between an agent and its MCP servers over stdio (`wrap`) or HTTP (`serve`), scans tool results and resource contents for prompt injection, masks personal data, enforces access by tool, role and dangerous capability combination, pins a server's tool definitions and writes every decision to a hash-chained audit log. Anyone wiring MCP servers into agents can try it by cloning and building the repository; it is not published on npm.

Open-Source TypeScript Node.js MCP +2 more
September 2026 — Ongoing

Comments

Sign in with your GitHub account to join the discussion. Comments are stored in GitHub Discussions.

Related Posts

Search the site

Start typing to search posts, projects and pages.

Esc to close Powered by Pagefind