Lesson 4 of 7
API Authentication - API Key, Bearer Token & JWT Concept
REST APIs are stateless - no sessions. Authentication is done per-request via tokens. API key authentication is simple (good for server-to-server). Bearer token (opaque token stored in DB) is the standard for user-facing APIs. JWT (JSON Web Token) is a self-contained token - the server can verify it without a DB lookup, but cannot revoke it easily.
API Key, Bearer Token & JWT Concept
<?php
declare(strict_types=1);
// ── Strategy 1: API Key Authentication ───────────────────────
// Best for: server-to-server, webhook callers, public read APIs
// Usage: X-API-Key: sk_live_abc123 header OR ?api_key= query param
class ApiKeyAuthMiddleware {
public function __construct(private readonly PDO $pdo) {}
public function authenticate(ApiRequest $req): ?array {
$key = $req->apiKey();
if (empty($key)) return null;
$stmt = $this->pdo->prepare(
"SELECT ak.*, u.name, u.email, u.role
FROM api_keys ak
JOIN users u ON u.id = ak.user_id
WHERE ak.key_hash = :hash AND ak.active = 1 AND (ak.expires_at IS NULL OR ak.expires_at > UTC_TIMESTAMP())
LIMIT 1"
);
$stmt->execute([":hash" => hash("sha256", $key)]); // store hash, not raw key
$apiKey = $stmt->fetch();
if ($apiKey) {
// Update last_used_at (async or queue in production)
$this->pdo->prepare("UPDATE api_keys SET last_used_at = UTC_TIMESTAMP() WHERE id = :id")
->execute([":id" => $apiKey["id"]]);
}
return $apiKey ?: null;
}
}
// ── Strategy 2: Bearer Token (Opaque Token in DB) ─────────────
// Best for: user-facing apps, mobile apps
// Usage: Authorization: Bearer {token}
class BearerTokenAuthMiddleware {
public function __construct(private readonly PDO $pdo) {}
public function authenticate(ApiRequest $req): ?array {
$token = $req->bearerToken();
if (empty($token)) return null;
$hash = hash("sha256", $token);
$stmt = $this->pdo->prepare(
"SELECT t.*, u.id AS user_id, u.name, u.email, u.role
FROM personal_access_tokens t
JOIN users u ON u.id = t.user_id
WHERE t.token_hash = :hash AND t.expires_at > UTC_TIMESTAMP()
LIMIT 1"
);
$stmt->execute([":hash" => $hash]);
return $stmt->fetch() ?: null;
}
public function createToken(int $userId, string $name, int $ttlDays = 30): string {
$token = bin2hex(random_bytes(40)); // 80-char hex token
$hash = hash("sha256", $token);
$this->pdo->prepare(
"INSERT INTO personal_access_tokens (user_id, name, token_hash, expires_at, created_at)
VALUES (:uid, :name, :hash, DATE_ADD(UTC_TIMESTAMP(), INTERVAL :days DAY), UTC_TIMESTAMP())"
)->execute([":uid" => $userId, ":name" => $name, ":hash" => $hash, ":days" => $ttlDays]);
return $token; // return ONCE - never stored in plain text
}
public function revokeToken(string $token): void {
$hash = hash("sha256", $token);
$this->pdo->prepare("DELETE FROM personal_access_tokens WHERE token_hash = :hash")
->execute([":hash" => $hash]);
}
}
// ── Strategy 3: JWT - Concept & Structure ─────────────────────
// JWT = JSON Web Token - self-contained, signed token
// Structure: base64url(header).base64url(payload).signature
//
// Header: {"alg": "HS256", "typ": "JWT"}
// Payload: {"sub": "1", "name": "Alice", "role": "admin", "exp": 1800000000}
// Signature: HMAC-SHA256(header + "." + payload, SECRET_KEY)
//
// ── JWT Advantages vs Opaque Token ───────────────────────────
// ✅ Stateless - server verifies signature WITHOUT database lookup (scales)
// ✅ Self-contained - payload carries user info (no DB join needed)
// ✅ Cross-service - microservices can verify without calling auth service
//
// ── JWT Disadvantages ─────────────────────────────────────────
// ❌ Cannot be revoked before expiry (must wait for exp)
// ❌ Secret key compromise = ALL tokens compromised
// ❌ Payload not encrypted (base64 is just encoding - anyone can read claims)
//
// ── JWT use in PHP - use firebase/php-jwt or lcobusc/php-jwt ──
// composer require firebase/php-jwt
// Conceptual (without library):
function jwtConcept(): string {
$header = base64_encode(json_encode(["alg" => "HS256", "typ" => "JWT"]));
$payload = base64_encode(json_encode([
"sub" => 1,
"name" => "Alice",
"role" => "admin",
"iat" => time(),
"exp" => time() + 3600,
]));
$signature = hash_hmac("sha256", "$header.$payload", $_ENV["JWT_SECRET"]);
return "$header.$payload.$signature";
}
// ── API Auth Middleware - combined ────────────────────────────
class ApiAuthMiddleware {
public function __construct(private BearerTokenAuthMiddleware $bearer) {}
public function requireAuth(ApiRequest $req): array {
$user = $this->bearer->authenticate($req);
if ($user === null) ApiResponse::error(["message" => "Unauthenticated. Please provide a valid Bearer token."], 401)->send();
return $user;
}
public function requireRole(ApiRequest $req, string $role): array {
$user = $this->requireAuth($req);
if ($user["role"] !== $role && $user["role"] !== "admin") {
ApiResponse::error(["message" => "Insufficient permissions."], 403)->send();
}
return $user;
}
}Quick Quiz
Tip
Tip
Practice API Authentication API Key Bearer Token JWT Concept in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for API Authentication - API Key, Bearer Token & JWT Concept
Practice Task
Note
Practice Task - (1) Write a working example of API Authentication API Key Bearer Token JWT Concept from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with API Authentication API Key Bearer Token JWT Concept is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?