Authenticate requests from the Authorization: Bearer header using random opaque tokens or a properly validated token format.
The examples introduce the underlying control before showing a verification and an application-level safeguard.
What You Will Build
Authenticate requests from the Authorization: Bearer header using random opaque tokens or a properly validated token format.
Prerequisites
Use PHP 8.4 or newer, HTTPS for all authentication operations, and an application session or database where required. Example configuration values are placeholders, never production secrets.
Example 1: Basic Operation
Issue a 256-bit opaque bearer token and store only its digest.
<?php
$rawToken = bin2hex(random_bytes(32));
$storedHash = hash('sha256', $rawToken);
// Store $storedHash with user ID, scopes and expiry. Return $rawToken once.
echo strlen($rawToken);
Example 2: A Different Use Case
Parse the Authorization header without accepting credentials in the URL.
<?php
$header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (!is_string($header) || !preg_match('/^Bearer ([A-Za-z0-9._~-]+)$/D', $header, $m)) {
http_response_code(401); exit;
}
$tokenHash = hash('sha256', $m[1]);
// Resolve $tokenHash server-side and check status, expiry and scopes.
Practical Example: Checking the Result
Check token revocation, expiration and endpoint-specific authorization.
<?php
$requiredScope = 'orders:read';
$tokenRecord = ['active' => true, 'expires_at' => time() + 60, 'scopes' => ['orders:read']];
if (!$tokenRecord['active'] || $tokenRecord['expires_at'] <= time() || !in_array($requiredScope, $tokenRecord['scopes'], true)) {
http_response_code(403); exit;
}
echo 'Authorized scope';
Important Behavior and Edge Cases
TLS is mandatory; verify expiration, revocation and scopes. Do not log bearer credentials or accept them in query strings.
Enforce controls on the server, test denial paths and do not assume that a snippet alone implements an entire production workflow.
Comparison with Related Functions
| Approach | Key distinction |
|---|---|
| Implementing API Authentication with Bearer Tokens | Authenticate requests from the Authorization: Bearer header using random opaque tokens or a properly validated token format. |
| Related technique | Opaque tokens can be stored as HMAC/SHA-256 digests; JWTs also need strict issuer, audience, algorithm and signature checks. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Confusing this operation with a neighboring cryptographic or security mechanism | Opaque tokens can be stored as HMAC/SHA-256 digests; JWTs also need strict issuer, audience, algorithm and signature checks. |
| Ignoring a security prerequisite or failure case | TLS is mandatory; verify expiration, revocation and scopes. Do not log bearer credentials or accept them in query strings. |
Key Takeaways
- Authenticate requests from the Authorization: Bearer header using random opaque tokens or a properly validated token format.
- TLS is mandatory; verify expiration, revocation and scopes. Do not log bearer credentials or accept them in query strings.
- Opaque tokens can be stored as HMAC/SHA-256 digests; JWTs also need strict issuer, audience, algorithm and signature checks.
Apply this behavior to a real application only after confirming the required extension, configuration and failure handling on the deployment runtime.