JWT in PHP: Secure Authentication for APIs (Complete Example)

JWT authentication in a PHP API with login and protected routes

Quick answer: A JWT is a signed token that your PHP API returns at login and the client sends with every request in the Authorization: Bearer header, with no session on the server. Sign it with HMAC SHA-256 and a strong secret key, set a short expiration (exp), and check the signature, the algorithm and the expiration before letting a request into a protected route. Never put passwords or sensitive data inside the token.

What is JWT and why use it in PHP APIs?

JWT (JSON Web Token) is an open standard for stateless authentication, widely used in REST APIs. Instead of a session on the server, the user receives a signed token and sends it with each request.

JWT works well for:

  • REST APIs
  • Separate frontends (React, Vue, mobile apps)
  • Scaling across servers (no shared session storage)

The JWT authentication flow

  1. The user logs in (email and password)
  2. The API checks the credentials
  3. The API creates a signed JWT
  4. The frontend stores the token
  5. Requests send Authorization: Bearer TOKEN

The basic structure of a JWT

HEADER.PAYLOAD.SIGNATURE
  • Header: the algorithm (HS256) and type
  • Payload: the claims (user ID, role, expiration)
  • Signature: the HMAC of header and payload with the secret key

The payload is only Base64URL-encoded, not encrypted: anyone holding the token can read it. That is why it must never contain passwords or private data.

JWT in plain PHP (no library)

To show how it works, we will implement JWT by hand. In production, prefer a maintained library such as firebase/php-jwt, which handles more edge cases.

1) Helper functions

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

function base64UrlDecode(string $data): string|false {
  $padded = str_pad(strtr($data, '-_', '+/'), strlen($data) + (4 - strlen($data) % 4) % 4, '=');
  return base64_decode($padded, true);
}

2) Generate a JWT

<?php
function generateJWT(array $payload, string $secret, int $expSeconds = 3600): string {
  $header = ['alg' => 'HS256', 'typ' => 'JWT'];

  $payload['iat'] = time();
  $payload['exp'] = time() + $expSeconds;

  $base64Header  = base64UrlEncode(json_encode($header));
  $base64Payload = base64UrlEncode(json_encode($payload));

  $signature = hash_hmac('sha256', "$base64Header.$base64Payload", $secret, true);

  return "$base64Header.$base64Payload." . base64UrlEncode($signature);
}

3) Validate a JWT

<?php
function validateJWT(string $jwt, string $secret): array|false {
  $parts = explode('.', $jwt);
  if (count($parts) !== 3) return false;

  [$header64, $payload64, $signature64] = $parts;

  // Only accept the algorithm we issue (never trust "alg" blindly)
  $header = json_decode((string) base64UrlDecode($header64), true);
  if (($header['alg'] ?? '') !== 'HS256') return false;

  $expected = base64UrlEncode(hash_hmac('sha256', "$header64.$payload64", $secret, true));
  if (!hash_equals($expected, $signature64)) return false;

  $data = json_decode((string) base64UrlDecode($payload64), true);
  if (!is_array($data) || !isset($data['exp']) || $data['exp'] < time()) return false;

  return $data;
}

hash_equals compares in constant time, so the signature check doesn't leak timing information.

Login endpoint that issues a JWT

<?php
// POST /api/login
header('Content-Type: application/json; charset=utf-8');

$secret = getenv('JWT_SECRET'); // a long random string, never in the code or the repository
$data = json_decode(file_get_contents('php://input'), true) ?? [];
$email = trim($data['email'] ?? '');
$password = $data['password'] ?? '';

$stmt = $pdo->prepare('SELECT id, email, role, password_hash FROM users WHERE email = :email LIMIT 1');
$stmt->execute([':email' => $email]);
$user = $stmt->fetch();

if (!$user || !password_verify($password, $user['password_hash'])) {
  http_response_code(401);
  echo json_encode(['error' => 'Invalid email or password']);
  exit;
}

$token = generateJWT([
  'sub'  => $user['id'],
  'role' => $user['role']
], $secret, 3600);

echo json_encode(['token' => $token, 'expires_in' => 3600]);

The query uses a prepared statement; see how to prevent SQL injection with PDO. Generate the secret once with something like bin2hex(random_bytes(32)).

Protecting routes with JWT

<?php
function bearerToken(): ?string {
  $auth = $_SERVER['HTTP_AUTHORIZATION']
       ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION']
       ?? (function_exists('getallheaders') ? (getallheaders()['Authorization'] ?? '') : '');
  return preg_match('/^Bearer\s+(\S+)$/i', $auth, $m) ? $m[1] : null;
}

$token = bearerToken();
$user = $token ? validateJWT($token, getenv('JWT_SECRET')) : false;

if (!$user) {
  http_response_code(401);
  header('WWW-Authenticate: Bearer');
  echo json_encode(['error' => 'Unauthorized']);
  exit;
}

// $user['sub'] and $user['role'] are now trusted

Apache not passing the Authorization header

On many Apache + PHP setups (CGI/FastCGI), the Authorization header never reaches PHP, so every request looks unauthenticated. Add this to .htaccess:

CGIPassAuth On

or, on older Apache versions:

RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

JWT and CORS

If your frontend is on another domain, always allow the Authorization header in the preflight response:

header("Access-Control-Allow-Headers: Content-Type, Authorization");

JWT security best practices

  • Always use HTTPS
  • Keep access tokens short-lived (15 to 60 minutes)
  • Avoid storing the JWT in localStorage when you can; an httpOnly cookie is safer against XSS
  • Use a refresh token for long sessions
  • Never expose the secret, and rotate it if it leaks (all tokens become invalid)
  • Check the algorithm, the signature and exp on every request

Common JWT mistakes in PHP

  • Using a weak or hard-coded secret
  • Not checking the expiration
  • Not checking the signature, or accepting whatever alg the token says
  • Putting sensitive data in the payload
  • Returning 403 instead of 401 for a missing or invalid token (401 means "not authenticated"; 403 means "authenticated but not allowed")

To see where JWT fits in a full API, read how to create a REST API in plain PHP.

More in PHP