Refresh Tokens in PHP: Short-Lived JWTs with Secure Rotation

Refresh tokens in PHP with short-lived JWT access tokens and secure rotation

Quick answer: Issue a short-lived JWT access token (10 to 15 minutes) sent in the Authorization header, plus a long-lived random refresh token. Store only a SHA-256 hash of the refresh token in the database. On POST /auth/refresh, look it up by hash, check that it isn't expired or revoked, revoke it, and issue a new pair (rotation). If a revoked token is used again, revoke the whole session. Browsers keep the refresh token in an httpOnly cookie; mobile apps keep it in private storage.

Short-lived access tokens limit the damage if one leaks, but nobody wants to type their password every 15 minutes. Refresh tokens solve that: a second, longer-lived credential that can only be used to get new access tokens, and that the server can revoke at any time. This guide builds the complete flow in plain PHP with PDO.

Access token vs. refresh token

Access tokenRefresh token
FormatJWT (signed, self-contained)Random string (opaque)
Lifetime10 to 15 minutes7 to 30 days
Sent toEvery API endpointOnly /auth/refresh and /auth/logout
Checked against the databaseNo (signature and expiry only)Yes, every time
Can be revokedOnly by waiting for it to expireImmediately

The access token is fast to check because the API doesn't touch the database. The refresh token is checked against the database, which is what makes revocation possible.

The flow

  1. POST /auth/login: checks the password, returns an access token and a refresh token;
  2. The client calls the API with Authorization: Bearer <access token>;
  3. When the access token expires, the API returns 401;
  4. The client calls POST /auth/refresh with the refresh token;
  5. The API revokes the old refresh token and returns a new pair;
  6. POST /auth/logout revokes the refresh token.

1. The refresh_tokens table

CREATE TABLE refresh_tokens (
    id          BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id     BIGINT NOT NULL,
    family_id   CHAR(32) NOT NULL,           -- one per login session
    token_hash  CHAR(64) NOT NULL,           -- SHA-256 of the token
    expires_at  DATETIME NOT NULL,
    revoked_at  DATETIME NULL,
    created_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    user_agent  VARCHAR(255) NULL,
    ip          VARCHAR(45) NULL,
    UNIQUE KEY uniq_token_hash (token_hash),
    KEY idx_user (user_id),
    KEY idx_family (family_id)
);

Never store the token itself: if the database leaks, the attacker gets nothing usable. Because the token is 64 random bytes, a fast SHA-256 hash is safe here, and unlike password_hash() it can be looked up directly with an index, without scanning rows.

The family_id groups all tokens created by one login, so a whole session can be revoked at once.

2. Helper functions

<?php

const ACCESS_TTL  = 900;       // 15 minutes
const REFRESH_TTL = 2592000;   // 30 days

function newRefreshToken(): string
{
    return bin2hex(random_bytes(32));   // 64 hex characters
}

function hashToken(string $token): string
{
    return hash('sha256', $token);
}

function storeRefreshToken(PDO $pdo, int $userId, string $familyId, string $token): void
{
    $stmt = $pdo->prepare('
        INSERT INTO refresh_tokens (user_id, family_id, token_hash, expires_at, user_agent, ip)
        VALUES (:uid, :fam, :hash, :exp, :ua, :ip)
    ');
    $stmt->execute([
        ':uid'  => $userId,
        ':fam'  => $familyId,
        ':hash' => hashToken($token),
        ':exp'  => date('Y-m-d H:i:s', time() + REFRESH_TTL),
        ':ua'   => mb_substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 255),
        ':ip'   => $_SERVER['REMOTE_ADDR'] ?? null,
    ]);
}

function issueAccessToken(array $user): string
{
    // Use your JWT code or library here: HS256 with a secret from the environment,
    // claims sub, role, iat and exp = time() + ACCESS_TTL.
    return createJwt(['sub' => (int) $user['id'], 'role' => $user['role']], ACCESS_TTL);
}

function sendTokens(array $user, string $refresh): never
{
    // Browsers: refresh token in an httpOnly cookie, scoped to the auth routes
    setcookie('refresh_token', $refresh, [
        'expires'  => time() + REFRESH_TTL,
        'path'     => '/api/auth',
        'secure'   => true,
        'httponly' => true,
        'samesite' => 'Strict',
    ]);

    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        'access_token'  => issueAccessToken($user),
        'expires_in'    => ACCESS_TTL,
        'refresh_token' => $refresh,   // for mobile apps; web clients can ignore it
    ]);
    exit;
}

For the JWT itself (signing, validating, the secret), see JWT authentication in PHP. If your API serves only browsers, you can leave refresh_token out of the JSON so JavaScript never sees it.

3. Login

<?php
// POST /api/auth/login

$user = checkCredentials($pdo, $email, $password);   // password_verify(); returns null on failure
if ($user === null) {
    http_response_code(401);
    echo json_encode(['message' => 'Invalid email or password.']);
    exit;
}

$refresh = newRefreshToken();
storeRefreshToken($pdo, (int) $user['id'], bin2hex(random_bytes(16)), $refresh);
sendTokens($user, $refresh);

Protect this endpoint with a strict rate limit. See rate limiting a PHP API.

4. Refresh with rotation and reuse detection

<?php
// POST /api/auth/refresh

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

if (!is_string($refresh) || $refresh === '') {
    http_response_code(401);
    echo json_encode(['message' => 'Refresh token missing.']);
    exit;
}

$pdo->beginTransaction();

$stmt = $pdo->prepare('SELECT * FROM refresh_tokens WHERE token_hash = :h FOR UPDATE');
$stmt->execute([':h' => hashToken($refresh)]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

// Unknown or expired token
if (!$row || strtotime($row['expires_at']) < time()) {
    $pdo->rollBack();
    http_response_code(401);
    echo json_encode(['message' => 'Session expired. Please log in again.']);
    exit;
}

// Token already used: someone may have stolen it. Revoke the whole session.
if ($row['revoked_at'] !== null) {
    $pdo->prepare('UPDATE refresh_tokens SET revoked_at = NOW() WHERE family_id = :f AND revoked_at IS NULL')
        ->execute([':f' => $row['family_id']]);
    $pdo->commit();
    error_log("Refresh token reuse detected for user {$row['user_id']}");
    http_response_code(401);
    echo json_encode(['message' => 'Session revoked. Please log in again.']);
    exit;
}

// Rotate: revoke the current token and issue a new one in the same family
$pdo->prepare('UPDATE refresh_tokens SET revoked_at = NOW() WHERE id = :id')
    ->execute([':id' => $row['id']]);

$newRefresh = newRefreshToken();
storeRefreshToken($pdo, (int) $row['user_id'], $row['family_id'], $newRefresh);

$pdo->commit();

$user = loadActiveUser($pdo, (int) $row['user_id']);   // fresh role; null if blocked or deleted
if ($user === null) {
    http_response_code(401);
    echo json_encode(['message' => 'Account unavailable.']);
    exit;
}

sendTokens($user, $newRefresh);

Key points:

  • Lookup by hash: one indexed query, no loops over rows;
  • Transaction with FOR UPDATE: two simultaneous refreshes with the same token can't both succeed;
  • Reuse detection: a legitimate client never sends a revoked token. If one arrives, either the client has a bug or an attacker has a copy, and revoking the family logs both out;
  • Fresh user data: the role and status come from the database on every refresh, so a blocked user stops getting tokens within 15 minutes.

Clients must refresh one request at a time. If several requests fail with 401 together, only one should refresh and the others should wait for the result; otherwise the second refresh uses a token that was just rotated and triggers reuse detection. On Android this is shown in automatic JWT refresh with OkHttp.

5. Logout

<?php
// POST /api/auth/logout

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

if (is_string($refresh) && $refresh !== '') {
    $stmt = $pdo->prepare('SELECT family_id FROM refresh_tokens WHERE token_hash = :h');
    $stmt->execute([':h' => hashToken($refresh)]);
    if ($family = $stmt->fetchColumn()) {
        $pdo->prepare('UPDATE refresh_tokens SET revoked_at = NOW() WHERE family_id = :f AND revoked_at IS NULL')
            ->execute([':f' => $family]);
    }
}

setcookie('refresh_token', '', [
    'expires' => time() - 3600, 'path' => '/api/auth',
    'secure' => true, 'httponly' => true, 'samesite' => 'Strict',
]);

http_response_code(204);

"Log out of all devices" is the same update with WHERE user_id = :uid. Do it automatically when the user changes the password.

6. Cleaning up

Delete old rows with a daily cron job:

DELETE FROM refresh_tokens WHERE expires_at < NOW() - INTERVAL 7 DAY;

Where should the client keep the tokens?

  • Browser: refresh token in the httpOnly cookie (JavaScript can't read it, so XSS can't steal it); access token in memory, not in localStorage;
  • Mobile app: both tokens in the app's private storage, ideally encrypted with a key from the Android Keystore or iOS Keychain.

If the front-end runs on another domain, the cookie needs SameSite=None; Secure and the API needs CORS with credentials; see CORS in PHP.

Common mistakes

  • Storing the refresh token in plain text in the database;
  • Looking it up with password_verify() in a loop over recent rows (slow, and misses older tokens);
  • Never rotating, so a stolen refresh token works for weeks;
  • Long-lived access tokens (days), which defeat the purpose;
  • Putting the role in the refresh flow from the old token instead of reloading the user;
  • Not revoking tokens on logout and password change;
  • Running authentication on the CORS preflight, which breaks the refresh call in browsers.

Conclusion

Short-lived JWTs plus rotating refresh tokens give you sessions that are both convenient and revocable: the API checks access tokens without touching the database, and every refresh passes through a single indexed lookup that can be revoked, rotated and audited. For the status codes the client should expect, see 401 vs. 403 in PHP APIs.

Frequently asked questions

Should the refresh token be a JWT?

It doesn't need to be. A random opaque string checked against the database is simpler and easier to revoke.

How long should tokens last?

Typically 10 to 15 minutes for access tokens and 7 to 30 days for refresh tokens, depending on how sensitive the app is.

Why SHA-256 and not password_hash for refresh tokens?

The token has 256 bits of randomness, so it can't be brute-forced; a fast hash is safe and allows an indexed lookup. password_hash is for low-entropy secrets like passwords.

Where should a web app store the refresh token?

In an httpOnly, Secure cookie scoped to the auth routes, so JavaScript can't read it.

What happens if two tabs refresh at the same time?

One succeeds and the other uses a revoked token. Coordinate refreshes in the client (one at a time), or allow a few seconds of grace for the token that was just rotated.

More in PHP