Skip to content
Tutorials Center
My learning

Topics

Lesson 101 of 147 ยท Security

Tokens, JWT and OAuth Flows

Understand signed tokens in PHP - build and verify HS256 JWTs with hash_hmac, handle expiry and algorithm pinning, and follow the OAuth 2 authorization code flow with PKCE.

Sessions store state on the server and give the browser a cookie. That works well for a single website, but it gets awkward when a mobile app, a single-page front end and three backend services all need to know who the caller is. A common answer is the token: a string the client sends with each request, which the server can check without looking anything up. The best-known format is the JSON Web Token (JWT), and the best-known protocol for handing tokens to third-party apps is OAuth 2.

This lesson shows what a JWT really is by building one with hash_hmac(), then covers expiry, the classic mistakes (the alg header trap, secrets in tokens, no revocation), and finishes with an overview of the OAuth 2 authorization code flow with PKCE. It builds on Cryptography, Sessions and Web Security Basics.

In production, prefer a maintained library (for example firebase/php-jwt or lcobucci/jwt) and an OAuth library such as league/oauth2-server or league/oauth2-client. Writing the pieces yourself is the best way to understand them, but not the best way to ship them.

Sessions or tokens?

Server-side session Self-contained token (JWT)
What the client holds Random session ID Signed data (user ID, expiry, ...)
Server needs storage? Yes, per session No lookup needed to verify
Revoke immediately Easy: delete the session Hard: valid until it expires
Best for One website, server-rendered pages APIs, mobile apps, service-to-service calls

Neither is "more secure" by default. For a classic PHP website, sessions are usually simpler and safer. Tokens shine when many independent parties must verify identity without sharing a database.

Anatomy of a JWT

A JWT has three parts separated by dots, each encoded with base64url (base64 with - and _ instead of + and /, and no = padding):

TEXT
header.payload.signature
  • The header names the algorithm: {"alg":"HS256","typ":"JWT"}.
  • The payload holds claims, for example sub (subject, the user), iss (issuer), aud (audience), iat (issued at), exp (expires at) and your own fields.
  • The signature is an HMAC of header.payload with a secret key (HS256), or a signature made with a private key (RS256, ES256).

Crucially, the payload is encoded, not encrypted. Anyone holding the token can read it. The signature only guarantees it was not altered.

flowchart LR
    H["Header JSON"] --> E1["base64url"]
    P["Payload JSON"] --> E2["base64url"]
    E1 --> J["header.payload"]
    E2 --> J
    J --> S["HMAC-SHA256 with secret"]
    S --> E3["base64url"]
    J --> T["Token = header.payload.signature"]
    E3 --> T

The signature covers the first two parts, so changing any claim invalidates the token.

Building and reading a token

PHP Creating an HS256 token by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Anyone can decode the payload, which is why you must never put passwords, card numbers or other secrets into a JWT.

Verifying a token correctly

Verification has to do several things in a fixed order, and skipping any of them is a vulnerability:

  1. Split into exactly three parts.
  2. Decode the header and check that alg is the algorithm you expect. Never let the token choose.
  3. Recompute the signature and compare it with hash_equals() (constant time).
  4. Only then trust the payload: check exp, nbf (not before), iss and aud.

The famous alg attacks exploited libraries that obeyed the token's header: a token with "alg":"none" and no signature, or a public key being reused as an HMAC secret. Pinning the algorithm on the server removes both.

PHP A strict verifier with expiry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

All four outcomes matter: the valid token passes, the edited payload fails the signature check, alg: none fails the algorithm check, and the same token a bit later fails on exp.

Lifetimes, refresh tokens and revocation

A JWT cannot be "taken back" before it expires, because verifiers do not ask anyone. Real systems cope by combining:

  • Short-lived access tokens (5 to 15 minutes).
  • Refresh tokens: long-lived, random, stored server-side (hashed) so they can be revoked. The client trades one for a new access token. Rotate them on every use.
  • A denylist of token IDs (jti claim) for emergencies, which brings back some server state.

Where does the client keep the token? In a browser, storing it in localStorage exposes it to any script that runs on your page (XSS). Many teams instead keep it in an HttpOnly, Secure, SameSite cookie, which then needs CSRF thought again. Native apps use the platform's secure storage.

Also remember: HS256 uses one shared secret that both signs and verifies, so every service that can verify can also forge. When many services only need to check tokens, use an asymmetric algorithm (RS256 or ES256): the identity provider signs with a private key, and others verify with the public key. PHP's openssl_sign() and openssl_verify() support this.

OAuth 2 in one picture

OAuth 2 is not a token format, it is a framework for letting an application act on a user's behalf without the user giving the app their password. "Sign in with Google" and "allow this app to read your calendar" are OAuth 2 (plus OpenID Connect on top for identity).

The four roles:

  • Resource owner: the user.
  • Client: the application that wants access (your PHP app).
  • Authorization server: authenticates the user and issues tokens.
  • Resource server: the API that accepts access tokens.

The recommended flow for web apps is the authorization code flow, with PKCE (Proof Key for Code Exchange):

sequenceDiagram
    participant U as User (browser)
    participant A as Your PHP app
    participant S as Authorization server
    participant R as Resource API
    A->>U: Redirect to /authorize with client_id, redirect_uri, scope, state, code_challenge
    U->>S: Sign in and approve access
    S->>U: Redirect to redirect_uri?code=...&state=...
    U->>A: Browser follows redirect
    A->>A: Check state equals the stored value
    A->>S: POST /token with code and code_verifier
    S->>A: access_token, refresh_token, expires_in
    A->>R: GET /me with Authorization: Bearer access_token
    R->>A: Protected data

The browser only carries a short-lived code; the real tokens travel server to server.

Why each piece exists:

  • state: a random value your app stores in the session and checks on return. It blocks forged callbacks (a CSRF variant).
  • redirect_uri: must match one registered in advance exactly, so codes go only to your app.
  • code: one-time and short-lived; useless without the client authenticating or proving PKCE.
  • PKCE: before the redirect, your app creates a random code_verifier and sends only its hash, the code_challenge. When exchanging the code it sends the original verifier. An attacker who steals the code cannot redeem it.

Here is the PKCE and state part, which you can run; the HTTP calls to the server are described in comments:

PHP State and PKCE values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In real code, use random_bytes(32) for both values, keep them in the session, and send the token request with curl:

PHP
// POST https://auth.example.com/token (application/x-www-form-urlencoded)
// grant_type=authorization_code&code=...&redirect_uri=...
// &client_id=my-php-app&code_verifier=...   (+ client_secret for confidential clients)

Access tokens: JWT or opaque?

OAuth does not require access tokens to be JWTs. Some servers issue opaque random strings that the resource server validates by calling the authorization server's introspection endpoint. That makes revocation instant at the cost of a network call. JWT access tokens avoid the call but cannot be revoked early. Both are valid; pick based on your revocation needs.

Checklist

  • Pin the algorithm; reject none; compare signatures with hash_equals().
  • Always validate exp, and also iss and aud.
  • Keep payloads small and free of secrets; remember they are readable.
  • Use long, random secrets (32+ bytes) for HS256, or asymmetric keys when many verifiers exist.
  • Short access tokens plus rotating, revocable refresh tokens.
  • Use authorization code flow with PKCE and a checked state; register exact redirect URIs; never use the implicit flow.
  • Serve everything over HTTPS.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Who can read the claims inside a signed (HS256) JWT?

    A JWT signature proves integrity, not secrecy. Do not put sensitive data in the payload.
  2. 2. Why must a verifier pin the expected algorithm instead of trusting the header's alg?

    If the token chooses how it is checked, an attacker controls the check. The server decides the algorithm.
  3. 3. What is the purpose of the state parameter in the OAuth 2 authorization code flow?

    You store a random state before redirecting and compare it on return, which defeats forged callbacks.
  4. 4. How does PKCE protect a stolen authorization code?

    The server stores the code_challenge (a hash). Redeeming needs the matching code_verifier, which an interceptor does not have.
  5. 5. Which is the best way to limit the damage of a leaked JWT access token?

    A short exp bounds the window of misuse; refresh tokens stored server-side can be revoked.

Summary

  • A JWT is header.payload.signature, each part base64url-encoded; the signature protects integrity, not confidentiality.
  • Verify in order: structure, pinned algorithm, signature with hash_equals(), then exp, nbf, iss, aud.
  • Tokens cannot be revoked early without server state, so use short lifetimes and revocable refresh tokens.
  • OAuth 2 delegates access without sharing passwords; the authorization code flow with PKCE and a checked state is the modern default.
  • Use maintained libraries in production and HTTPS everywhere.

Next up: Two-Factor Auth and Passkeys.