JWT

suggest change

A JSON Web Token (JWT, pronounced "jot") is a compact, URL-safe string that carries a set of claims (a JSON object) plus a signature. Whoever has the key can check that the claims were issued by a trusted party and were not changed.

JWTs are used for:

This article covers creating and verifying JWTs in PHP. For getting tokens from an external provider and verifying OIDC ID tokens against a JWKS, see OAuth.

Anatomy of a JWT

A JWT is three base64url-encoded parts joined by dots: header.payload.signature.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsIm5hbWUiOiJKYW5lIiwiaWF0IjoxNzYwNjk2MDAwfQ.91KEuhSvVTaMQWS8pJjbs0XSTXNZ5fdyD_P3t-ZNEF8

The first two parts are just JSON. Anyone can read them, no key needed:

<?php
$jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsIm5hbWUiOiJKYW5lIiwiaWF0IjoxNzYwNjk2MDAwfQ.91KEuhSvVTaMQWS8pJjbs0XSTXNZ5fdyD_P3t-ZNEF8';

[$header, $payload, $signature] = explode('.', $jwt);

function base64url_decode(string $s): string
{
    return base64_decode(strtr($s, '-_', '+/'), true);
}

var_dump(json_decode(base64url_decode($header), true));
var_dump(json_decode(base64url_decode($payload), true));
echo strlen(base64url_decode($signature)), " bytes of signature\n";

Output:

array(2) {
  ["alg"]=>
  string(5) "HS256"
  ["typ"]=>
  string(3) "JWT"
}
array(3) {
  ["sub"]=>
  string(2) "42"
  ["name"]=>
  string(4) "Jane"
  ["iat"]=>
  int(1760696000)
}
32 bytes of signature

A signed JWT is not encrypted. Never put passwords, personal data you would not show the user, or other secrets in the payload. (Encrypted JWTs exist, called JWE, but they are rarely needed and poorly supported.)

The header's alg says how the signature was made. The common algorithms:

alg Type Key
HS256, HS384, HS512 HMAC with SHA-2 one shared secret signs and verifies
RS256, RS384, RS512, PS256 RSA private key signs, public key verifies
ES256, ES384 ECDSA private key signs, public key verifies
EdDSA Ed25519 private key signs, public key verifies
none no signature never accept this

Use HS256 when the same application issues and checks tokens. Use an asymmetric algorithm (RS256, ES256 or EdDSA) when other services must verify tokens but must not be able to create them.

Registered claims

The JWT spec (RFC 7519) defines short names for common claims. All are optional, but you should use them:

Claim Meaning Example
iss issuer: who created the token "https://api.example.com"
sub subject: who the token is about, usually a user id (a string) "42"
aud audience: who the token is for, a string or an array "https://api.example.com"
exp expiration time, Unix timestamp 1792256013
nbf not before, Unix timestamp 1792255113
iat issued at, Unix timestamp 1792255113
jti unique token id, for revocation or replay detection "c990b479..."

Add your own claims (roles, tenant, scope) next to them. Keep the payload small: the token is sent with every request.

HS256 by hand

You should use a library in real code, but writing it once shows what verification must do. This uses only built-in functions:

<?php
function base64url_encode(string $bytes): string
{
    return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
}

function base64url_decode(string $s): string|false
{
    return base64_decode(strtr($s, '-_', '+/'), true);
}

function jwt_sign(array $claims, string $secret): string
{
    $header  = base64url_encode(json_encode(['alg' => 'HS256', 'typ' => 'JWT']));
    $payload = base64url_encode(json_encode($claims));
    $sig     = hash_hmac('sha256', "$header.$payload", $secret, true);
    return "$header.$payload." . base64url_encode($sig);
}

function jwt_verify(string $jwt, string $secret): array
{
    $parts = explode('.', $jwt);
    if (count($parts) !== 3) {
        throw new UnexpectedValueException('Malformed token');
    }
    [$h, $p, $s] = $parts;

    $header = json_decode(base64url_decode($h) ?: '', true);
    // Never let the token pick the algorithm.
    if (($header['alg'] ?? null) !== 'HS256') {
        throw new UnexpectedValueException('Unexpected algorithm');
    }

    $expected = base64url_encode(hash_hmac('sha256', "$h.$p", $secret, true));
    if (!hash_equals($expected, $s)) {
        throw new UnexpectedValueException('Bad signature');
    }

    $claims = json_decode(base64url_decode($p) ?: '', true);
    if (!is_array($claims)) {
        throw new UnexpectedValueException('Bad payload');
    }
    if (isset($claims['exp']) && $claims['exp'] <= time()) {
        throw new UnexpectedValueException('Expired');
    }
    return $claims;
}

$secret = random_bytes(32);
$jwt = jwt_sign(['sub' => '42', 'iat' => time(), 'exp' => time() + 900], $secret);
echo $jwt, "\n";
print_r(jwt_verify($jwt, $secret));

// Replace the payload but keep the old signature: verification fails.
[$h, $p, $s] = explode('.', $jwt);
$forged = $h . '.' . base64url_encode(json_encode(['sub' => '1', 'exp' => time() + 900])) . '.' . $s;
try {
    jwt_verify($forged, $secret);
} catch (UnexpectedValueException $e) {
    echo $e->getMessage(), "\n";
}

Output:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsImlhdCI6MTc5MjI1NTExMywiZXhwIjoxNzkyMjU2MDEzfQ.xPNGoCnaOr9MgEKHEZ_P0IDQhs7EypL8KJhB7SotHWU
Array
(
    [sub] => 42
    [iat] => 1792255113
    [exp] => 1792256013
)
Bad signature

Three details matter:

firebase/php-jwt

firebase/php-jwt is the most widely used JWT library for PHP. It is small and has no dependencies. Version 7 requires PHP 8.0+ and rejects keys that are too short.

composer require firebase/php-jwt

Creating and verifying a token

<?php
require __DIR__ . '/vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

// At least 32 bytes for HS256. Generate once with:
//   php -r 'echo base64_encode(random_bytes(32)), "\n";'
// and load it from an environment variable or secrets store.
$secret = base64_decode('n0jYkZcXJ7vQ2c3m3F8l9m3m0U2kq3Jw6oXH8Yt3aKQ=');

$now = time();
$claims = [
    'iss'   => 'https://api.example.com',
    'aud'   => 'https://api.example.com',
    'sub'   => '42',
    'iat'   => $now,
    'nbf'   => $now,
    'exp'   => $now + 15 * 60,
    'jti'   => bin2hex(random_bytes(16)),
    'roles' => ['editor'],
];

$jwt = JWT::encode($claims, $secret, 'HS256');
echo $jwt, "\n\n";

$decoded = JWT::decode($jwt, new Key($secret, 'HS256'));
var_dump($decoded->sub, $decoded->roles);
echo date('H:i:s', $decoded->exp), "\n";

// Need an array instead of stdClass?
$asArray = json_decode(json_encode($decoded), true);
echo $asArray['roles'][0], "\n";

Output:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2FwaS5leGFtcGxlLmNvbSIsImF1ZCI6Imh0dHBzOi8vYXBpLmV4YW1wbGUuY29tIiwic3ViIjoiNDIiLCJpYXQiOjE3OTIyNTUxMzAsIm5iZiI6MTc5MjI1NTEzMCwiZXhwIjoxNzkyMjU2MDMwLCJqdGkiOiJjOTkwYjQ3OTcxODc1NmNlN2E3YTBmMTBjNTQwMmEyMSIsInJvbGVzIjpbImVkaXRvciJdfQ.1MgZ9oD4nRbXywkq2dNvEWsXaheDa7dqKQ6kFY1uokM

string(2) "42"
array(1) {
  [0]=>
  string(6) "editor"
}
16:53:50
editor

The Key object pairs the key with the one algorithm it may be used with. A token whose header names a different algorithm is rejected, which prevents algorithm confusion.

JWT::decode() verifies the signature and the time claims exp, nbf and iat. It does not check iss, aud or anything else; that is your job (see the API example below).

Handling errors

decode() throws a different exception for each kind of failure:

<?php
require __DIR__ . '/vendor/autoload.php';

use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;

$secret = str_repeat('k', 32);
$key    = new Key($secret, 'HS256');

function check(string $label, string $jwt, Key $key): void
{
    try {
        $claims = JWT::decode($jwt, $key);
        echo "$label: ok, sub={$claims->sub}\n";
    } catch (ExpiredException $e) {
        echo "$label: expired (", $e->getMessage(), ")\n";
    } catch (BeforeValidException $e) {
        echo "$label: not valid yet\n";
    } catch (SignatureInvalidException $e) {
        echo "$label: bad signature\n";
    } catch (UnexpectedValueException | DomainException | InvalidArgumentException $e) {
        // malformed token, wrong algorithm, bad JSON, key problems
        echo "$label: invalid (", $e->getMessage(), ")\n";
    }
}

$now = time();
check('valid',     JWT::encode(['sub' => '1', 'exp' => $now + 60], $secret, 'HS256'), $key);
check('expired',   JWT::encode(['sub' => '2', 'exp' => $now - 10], $secret, 'HS256'), $key);
check('future',    JWT::encode(['sub' => '3', 'nbf' => $now + 300], $secret, 'HS256'), $key);
check('other key', JWT::encode(['sub' => '4'], str_repeat('x', 32), 'HS256'), $key);
check('HS512',     JWT::encode(['sub' => '5'], str_repeat('k', 64), 'HS512'), $key);
check('garbage',   'not.a.jwt', $key);

// Allow a little clock skew between servers.
JWT::$leeway = 30;
check('leeway',    JWT::encode(['sub' => '6', 'exp' => $now - 10], $secret, 'HS256'), $key);
JWT::$leeway = 0;

try {
    JWT::encode(['sub' => '7'], 'short-secret', 'HS256');
} catch (DomainException $e) {
    echo 'encode: ', $e->getMessage(), "\n";
}

Output:

valid: ok, sub=1
expired: expired (Expired token)
future: not valid yet
other key: bad signature
HS512: invalid (Incorrect key for this algorithm)
garbage: invalid (Malformed UTF-8 characters)
leeway: ok, sub=6
encode: Provided key is too short

ExpiredException and BeforeValidException have getPayload(), which returns the (signature-verified) claims. That is useful for logging which user's token expired.

Don't show exception messages to API clients. Respond with a generic 401 and log the details.

Asymmetric keys: RS256, ES256, EdDSA

With an asymmetric algorithm only the auth server holds the private key. Every other service gets the public key and can verify tokens but cannot mint them.

Generate key pairs with the OpenSSL extension (or the openssl command line tool). Do this once and keep the private key outside the web root and out of version control:

<?php
// RSA 2048-bit or larger for RS256. php-jwt rejects smaller keys.
$key = openssl_pkey_new([
    'private_key_type' => OPENSSL_KEYTYPE_RSA,
    'private_key_bits' => 2048,
]);
openssl_pkey_export_to_file($key, __DIR__ . '/jwt-private.pem');
file_put_contents(__DIR__ . '/jwt-public.pem', openssl_pkey_get_details($key)['key']);

// EC P-256 for ES256: smaller keys and much shorter tokens.
$ec = openssl_pkey_new([
    'private_key_type' => OPENSSL_KEYTYPE_EC,
    'curve_name'       => 'prime256v1',
]);
openssl_pkey_export_to_file($ec, __DIR__ . '/jwt-ec-private.pem');
file_put_contents(__DIR__ . '/jwt-ec-public.pem', openssl_pkey_get_details($ec)['key']);

echo file_get_contents(__DIR__ . '/jwt-ec-public.pem');

Output (different every time):

-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEgmPw1rLGxs3VSmoY2zo6kc25j3RI
UN6TIqqSm+OZfZwJZTYHzKCqgpgSCmA/zclli1+gI1/EouQKsCumvypW1g==
-----END PUBLIC KEY-----

Signing and verifying looks the same as with HS256; only the keys differ:

<?php
require __DIR__ . '/vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

// Auth server: signs with the private key.
$privateKey = file_get_contents(__DIR__ . '/jwt-private.pem');
$jwt = JWT::encode(
    ['iss' => 'https://auth.example.com', 'sub' => '42', 'exp' => time() + 900],
    $privateKey,
    'RS256',
    'key-2026-10'          // "kid" header: which key signed this token
);

// Any other service: verifies with the public key only.
$publicKey = file_get_contents(__DIR__ . '/jwt-public.pem');
$claims = JWT::decode($jwt, new Key($publicKey, 'RS256'));
echo $claims->sub, "\n";

// ES256 works the same way.
$es = JWT::encode(['sub' => '42'], file_get_contents(__DIR__ . '/jwt-ec-private.pem'), 'ES256');
echo strlen($jwt), ' vs ', strlen($es), " characters\n";
echo JWT::decode($es, new Key(file_get_contents(__DIR__ . '/jwt-ec-public.pem'), 'ES256'))->sub, "\n";

// EdDSA (Ed25519) uses libsodium keys, base64-encoded.
$pair = sodium_crypto_sign_keypair();
$edPrivate = base64_encode(sodium_crypto_sign_secretkey($pair));
$edPublic  = base64_encode(sodium_crypto_sign_publickey($pair));
$ed = JWT::encode(['sub' => '42'], $edPrivate, 'EdDSA');
echo JWT::decode($ed, new Key($edPublic, 'EdDSA'))->sub, "\n";

Output:

42
490 vs 140 characters
42
42

(The RS256 token is longer partly because it has more claims, but an RSA-2048 signature alone is 256 bytes against 64 for ES256 and EdDSA.)

Key rotation with kid

To replace a signing key without logging everyone out, give each key an id, put it in the token's kid header, and accept several keys during the transition. Pass decode() an array of Key objects indexed by kid:

<?php
require __DIR__ . '/vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$keys = [
    'key-2026-07' => new Key(file_get_contents(__DIR__ . '/old-public.pem'), 'RS256'),
    'key-2026-10' => new Key(file_get_contents(__DIR__ . '/jwt-public.pem'), 'RS256'),
];

$privateKey = file_get_contents(__DIR__ . '/jwt-private.pem');
$jwt = JWT::encode(['sub' => '42'], $privateKey, 'RS256', 'key-2026-10');

// decode() picks the key named by the token's "kid" header.
// Pass a stdClass as the third argument to get the header back.
$headers = new stdClass();
$claims = JWT::decode($jwt, $keys, $headers);
echo $headers->kid, ' ', $claims->sub, "\n";

try {
    JWT::decode(JWT::encode(['sub' => '1'], $privateKey, 'RS256', 'nope'), $keys);
} catch (UnexpectedValueException $e) {
    echo $e->getMessage(), "\n";
}
try {
    JWT::decode(JWT::encode(['sub' => '1'], $privateKey, 'RS256'), $keys);
} catch (UnexpectedValueException $e) {
    echo $e->getMessage(), "\n";
}

Output:

key-2026-10 42
"kid" invalid, unable to lookup correct key
"kid" empty, unable to lookup correct key

The rotation procedure: add the new public key to the verifiers, start signing with the new private key, and remove the old public key once the longest-lived token signed with it has expired.

Publishing a JWKS

Instead of copying PEM files to every service, publish your public keys as a JSON Web Key Set at a URL such as /.well-known/jwks.json. Consumers fetch it and look keys up by kid, exactly as the OAuth article shows for Google's keys. Building the JWKS for an RSA key needs only the OpenSSL extension:

<?php
// jwks.php
function base64url_encode(string $bytes): string
{
    return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
}

function rsa_jwk(string $publicPem, string $kid): array
{
    $rsa = openssl_pkey_get_details(openssl_pkey_get_public($publicPem))['rsa'];
    return [
        'kty' => 'RSA',
        'use' => 'sig',
        'alg' => 'RS256',
        'kid' => $kid,
        'n'   => base64url_encode($rsa['n']),   // modulus
        'e'   => base64url_encode($rsa['e']),   // exponent
    ];
}

header('Content-Type: application/json');
header('Cache-Control: public, max-age=3600');
echo json_encode(['keys' => [
    rsa_jwk(file_get_contents(__DIR__ . '/jwt-public.pem'), 'key-2026-10'),
]], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

Output:

{
    "keys": [
        {
            "kty": "RSA",
            "use": "sig",
            "alg": "RS256",
            "kid": "key-2026-10",
            "n": "k0Jt4kN9rBEutXM1vygFAeAi7kOcRAjQDgFDtdAfeIskZ-Sk4LLQRf052sD13mhU5HEEO82Y3r2BVZqO_aEv-kecc1aDRAoyRCnqiz4FrwAGQ9atonimWYg3BP-TAK0yBw4KXmwX2PskaGKmIyUgjjK4qHUg1UBVbtStizuLidZBX3iS1rI5zcZ4RMqfRjzY-jn20iG9OneqvF-EiRyWJEq8SauxYac0GI7IjIG63l_6bm-dKvoL_VWQ37w-AnvAmaTIJgKmY7sStHb7K6TvZeYPlJLFdKu8M3r44OFcYTGqhybp15RhA-CWSMpKUqXFfwqPuaf4sCoIO-zlN0Ekxw",
            "e": "AQAB"
        }
    ]
}

A consumer verifies with JWT::decode($jwt, JWK::parseKeySet($jwks)).

Protecting an API with JWT access tokens

A complete, minimal setup: a login endpoint that issues a short-lived access token, and a helper that every protected endpoint calls.

jwt_auth.php:

<?php
require __DIR__ . '/vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

const JWT_ISSUER   = 'https://api.example.com';
const JWT_AUDIENCE = 'https://api.example.com';
const JWT_TTL      = 900; // 15 minutes

function jwt_secret(): string
{
    // 32+ random bytes, base64-encoded in an environment variable.
    return base64_decode(getenv('JWT_SECRET') ?: '', true)
        ?: throw new RuntimeException('JWT_SECRET is not set');
}

function issue_access_token(int $userId, array $roles): string
{
    $now = time();
    return JWT::encode([
        'iss'   => JWT_ISSUER,
        'aud'   => JWT_AUDIENCE,
        'sub'   => (string)$userId,
        'iat'   => $now,
        'exp'   => $now + JWT_TTL,
        'roles' => $roles,
    ], jwt_secret(), 'HS256');
}

function deny(int $status, string $error): never
{
    http_response_code($status);
    header('WWW-Authenticate: Bearer error="' . $error . '"');
    header('Content-Type: application/json');
    echo json_encode(['error' => $error]);
    exit;
}

function require_user(?string $role = null): stdClass
{
    $header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
    if (!preg_match('/^Bearer\s+(\S+)$/i', $header, $m)) {
        deny(401, 'invalid_request');
    }

    try {
        JWT::$leeway = 30;
        $claims = JWT::decode($m[1], new Key(jwt_secret(), 'HS256'));
    } catch (Throwable) {
        deny(401, 'invalid_token');
    }

    // php-jwt checks the signature and exp/nbf/iat, nothing else.
    if (($claims->iss ?? null) !== JWT_ISSUER
        || !in_array(JWT_AUDIENCE, (array)($claims->aud ?? []), true)) {
        deny(401, 'invalid_token');
    }
    if ($role !== null && !in_array($role, $claims->roles ?? [], true)) {
        deny(403, 'insufficient_scope');
    }
    return $claims;
}

login.php checks the password (see Verifying a password against a hash) and returns a token:

<?php
require __DIR__ . '/jwt_auth.php';

$pdo = new PDO('sqlite:' . __DIR__ . '/app.db');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$input = json_decode(file_get_contents('php://input'), true) ?? [];

$stmt = $pdo->prepare('SELECT id, password_hash, roles FROM users WHERE email = ?');
$stmt->execute([$input['email'] ?? '']);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user || !password_verify($input['password'] ?? '', $user['password_hash'])) {
    http_response_code(401);
    exit(json_encode(['error' => 'invalid_credentials']));
}

header('Content-Type: application/json');
echo json_encode([
    'access_token' => issue_access_token($user['id'], explode(',', $user['roles'])),
    'token_type'   => 'Bearer',
    'expires_in'   => JWT_TTL,
]);

reports.php is a protected endpoint:

<?php
require __DIR__ . '/jwt_auth.php';

$user = require_user('editor');

header('Content-Type: application/json');
echo json_encode(['user' => $user->sub, 'reports' => ['q3.pdf']]);

Trying it with the built-in server (JWT_SECRET=... php -S 127.0.0.1:8000):

$ curl -s -X POST localhost:8000/login.php -d '{"email":"jane@example.com","password":"s3cret"}'
{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3Mi...","token_type":"Bearer","expires_in":900}

$ curl -i localhost:8000/reports.php -H "Authorization: Bearer $TOKEN"
HTTP/1.1 200 OK
Content-Type: application/json

{"user":"42","reports":["q3.pdf"]}

$ curl -i localhost:8000/reports.php
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error="invalid_request"
Content-Type: application/json

{"error":"invalid_request"}

If $_SERVER['HTTP_AUTHORIZATION'] is empty under Apache with PHP-FPM, add CGIPassAuth On to .htaccess.

Expiration, refresh tokens and revocation

A JWT stays valid until exp, even if the user logs out, changes their password or is banned. You cannot "delete" it. The standard answer is to make access tokens short-lived (5 to 15 minutes) and pair them with a long-lived refresh token that is stored in your database and can be revoked.

The refresh token does not need to be a JWT. A random string is simpler, and storing only its hash means a database leak does not leak usable tokens:

<?php
// CREATE TABLE refresh_tokens (
//     token_hash TEXT PRIMARY KEY,
//     user_id    INTEGER NOT NULL,
//     expires_at INTEGER NOT NULL
// );

function create_refresh_token(PDO $pdo, int $userId): string
{
    $token = bin2hex(random_bytes(32));
    $pdo->prepare('INSERT INTO refresh_tokens VALUES (?, ?, ?)')
        ->execute([hash('sha256', $token), $userId, time() + 30 * 86400]);
    return $token;
}

// Returns the user id and deletes the token (each refresh token is single use).
function consume_refresh_token(PDO $pdo, string $token): ?int
{
    $stmt = $pdo->prepare(
        'DELETE FROM refresh_tokens WHERE token_hash = ? AND expires_at > ? RETURNING user_id'
    );
    $stmt->execute([hash('sha256', $token), time()]);
    $userId = $stmt->fetchColumn();
    return $userId === false ? null : (int)$userId;
}

$rt = create_refresh_token($pdo, 42);
var_dump(consume_refresh_token($pdo, $rt));
var_dump(consume_refresh_token($pdo, $rt)); // already used

Output:

int(42)
NULL

A refresh.php endpoint calls consume_refresh_token(), and on success returns a new access token and a new refresh token (rotation). Logout deletes the user's refresh tokens; after at most one access token lifetime the user is fully logged out.

DELETE ... RETURNING works in SQLite 3.35+, PostgreSQL and MariaDB. On MySQL, run a SELECT ... FOR UPDATE and DELETE inside a transaction instead.

If you need immediate revocation, give each access token a jti and keep a denylist of revoked jti values in a fast cache until their exp passes (see Cache). At that point you are doing a lookup on every request anyway, so consider whether plain sessions would be simpler.

JWT or sessions?

For a classic server-rendered PHP site, Sessions are usually the better choice: logout is instant, the browser handles the cookie, and nothing about the user is exposed to the client. JWTs pay off when:

If a browser single-page app does use JWTs, keep them out of localStorage, where any XSS bug can read them. Prefer an HttpOnly, Secure, SameSite cookie (see Cookies) and remember that cookies bring back the need for CSRF protection.

lcobucci/jwt

lcobucci/jwt is the other major library, used by Laravel Passport and many Symfony bundles. It has a fluent builder, typed tokens and explicit validation constraints, so forgetting to check iss or aud is harder.

composer require lcobucci/jwt lcobucci/clock
<?php
require __DIR__ . '/vendor/autoload.php';

use Lcobucci\Clock\SystemClock;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\UnencryptedToken;
use Lcobucci\JWT\Validation\Constraint\IssuedBy;
use Lcobucci\JWT\Validation\Constraint\PermittedFor;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
use Lcobucci\JWT\Validation\Constraint\StrictValidAt;
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;

$config = Configuration::forSymmetricSigner(
    new Sha256(),
    InMemory::base64Encoded('n0jYkZcXJ7vQ2c3m3F8l9m3m0U2kq3Jw6oXH8Yt3aKQ=')
);

$now = new DateTimeImmutable();
$token = $config->builder()
    ->issuedBy('https://api.example.com')
    ->permittedFor('https://api.example.com')
    ->relatedTo('42')
    ->identifiedBy(bin2hex(random_bytes(16)))
    ->issuedAt($now)
    ->canOnlyBeUsedAfter($now)
    ->expiresAt($now->modify('+15 minutes'))
    ->withClaim('roles', ['editor'])
    ->getToken($config->signer(), $config->signingKey());

$jwt = $token->toString();

// Validation: every check is explicit.
$parsed = $config->parser()->parse($jwt);
assert($parsed instanceof UnencryptedToken);

$constraints = [
    new SignedWith($config->signer(), $config->verificationKey()),
    new StrictValidAt(SystemClock::fromUTC(), new DateInterval('PT30S')), // 30 s leeway
    new IssuedBy('https://api.example.com'),
    new PermittedFor('https://api.example.com'),
];

try {
    $config->validator()->assert($parsed, ...$constraints);
    echo $parsed->claims()->get('sub'), ' ', implode(',', $parsed->claims()->get('roles')), "\n";
} catch (RequiredConstraintsViolated $e) {
    foreach ($e->violations() as $v) {
        echo $v->getMessage(), "\n";
    }
}

// A token for a different audience fails with a readable reason.
$other = $config->builder()
    ->permittedFor('https://other.example.com')
    ->issuedAt($now)->canOnlyBeUsedAfter($now)->expiresAt($now->modify('+1 minute'))
    ->getToken($config->signer(), $config->signingKey());
try {
    $config->validator()->assert($other, ...$constraints);
} catch (RequiredConstraintsViolated $e) {
    foreach ($e->violations() as $v) {
        echo $v->getMessage(), "\n";
    }
}

Output:

42 editor
The token was not issued by the given issuers
The token is not allowed to be used by this audience

parse() throws Lcobucci\JWT\Token\InvalidTokenStructure or Lcobucci\JWT\Encoding\CannotDecodeContent for malformed input, so catch those too in real code. For RS256 use Configuration::forAsymmetricSigner(new Lcobucci\JWT\Signer\Rsa\Sha256(), InMemory::file('private.pem'), InMemory::file('public.pem')).

Security checklist

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents