Receiving 401 Unauthorized from an authenticated REST endpoint after wiring up JSON Web Tokens rarely means your whole authentication design is broken—almost always one of five concrete mismatches sits in the path: Apache or PHP-FPM stripping the Authorization header before PHP ever sees it, a stray newline or Base64 encoding mistake on the HS256 secret, swapped RS256 keys, server clock drift failing exp/nbf checks, or browser CORS preflight rejecting headers.
Failure Matrix: Diagnosing JWT 401 & Signature Errors Fast
| Symptom / Server Error | Hidden Cause | Immediate Verified Fix |
|---|---|---|
Token works locally, returns Missing Bearer token on Hostinger / Apache |
Apache CGI/FastCGI/PHP-FPM drops HTTP_AUTHORIZATION before passing headers to PHP |
Add CGIPassAuth On (or RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]) to .htaccess |
Signature verification failed across two services sharing an HS256 key |
Trailing newline (`\n`) from cat/secret managers, shell trimming, or Base64 string decoded in Node vs raw string in PHP |
trim() file-loaded secrets and agree cleanly on UTF-8 bytes vs decoded Base64 bytes |
openssl_verify(): key param is not a valid public key (RS256) |
Verifier passed private key, stripped PEM headers, or corrupted \n inside single-line `.env` PEM strings |
Sign with private PEM, verify with SPKI public PEM (`-----BEGIN PUBLIC KEY-----`), and convert literal `\n` to newlines |
Random Expired token or Cannot handle token prior to errors |
Auth server and API container clocks differ by 10–90 seconds (`exp` / `nbf` / `iat` Unix timestamps) | Enable NTP time sync (`chrony`/`systemd-timesyncd`) and configure modest 15–30s leeway |
Browser sends OPTIONS → fails before GET/POST sends Bearer header |
CORS preflight response lacks Access-Control-Allow-Headers: Authorization |
Return 204 on preflight with explicit Authorization + Content-Type headers |
1. Apache / PHP-FPM Stripping the Authorization Header
This is the single most common production surprise when migrating a PHP or CodeIgniter API onto Apache + PHP-FPM or shared hosting. For historical CGI security reasons, Apache strips incoming Authorization: Bearer ... headers unless configured to forward them explicitly, leaving $_SERVER['HTTP_AUTHORIZATION'] completely empty!
# Add inside public/.htaccess (or Apache VirtualHost)
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
# Also supported directly on Apache 2.4.13+
CGIPassAuth On
In Nginx behind PHP-FPM, verify fastcgi_pass_header Authorization; is not overridden, and read defensively in PHP across both $_SERVER['HTTP_AUTHORIZATION'] and $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] (which Apache creates after internal `.htaccess` rewrites!):
<?php
function extractBearerToken(): ?string
{
$header = $_SERVER['HTTP_AUTHORIZATION']
?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION']
?? (function_exists('getallheaders') ? (getallheaders()['Authorization'] ?? null) : null);
if (!is_string($header) || !preg_match('/^\s*Bearer\s+(\S+)\s*$/i', $header, $m)) {
return null;
}
return $m[1];
}
2. Fixing HS256 Secret Mismatches & Asymmetric RS256 Key Bugs
When a token generated in PHP fails signature checks in Node.js (or vice versa), paste both the token and a test secret inside our client-side JWT Signer / Verifier to compare Base64URL signatures offline:
- Trailing Newlines: Reading a secret file via
file_get_contents()often keeps a trailing\nbyte, changing the HMAC digest completely. - Base64 vs Raw UTF-8: If Service A creates a 32-byte key and encodes it as Base64 inside `.env`, both signer and verifier must pass the exact same byte sequence (`Buffer.from(envSecret, 'base64')` in Node matching `base64_decode($envSecret)` in PHP).
- PEM Newlines in
.env: Storing multi-lineRS256public keys inside single-line `.env` secrets escapes newlines as literal `\n`. Always callstr_replace('\n', "\n", $pem)before passing keys into OpenSSL or `Key`.
3. Fixing Clock Skew (exp / nbf / iat) Safely Across PHP & Node.js
Servers drifting out of NTP sync reject valid short-lived access tokens (`nbf` in the future or `exp` prematurely elapsed). First check timedatectl status across API and identity hosts, then apply a tight verification leeway (for example 30 seconds—never hours):
<?php
// PHP (firebase/php-jwt v6+)
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
JWT::$leeway = 30; // Allows up to 30s clock drift for exp / nbf
$secret = trim((string) env('JWT_HS256_SECRET'));
try {
// Explicit single algorithm object prevents alg=none or RS/HS confusion attacks
$decoded = JWT::decode($token, new Key($secret, 'HS256'));
} catch (\Throwable $e) {
http_response_code(401);
header('WWW-Authenticate: Bearer error="invalid_token"');
exit;
}
// Node.js (jsonwebtoken)
const jwt = require('jsonwebtoken');
try {
const payload = jwt.verify(token, process.env.JWT_HS256_SECRET.trim(), {
algorithms: ['HS256'], // Strictly pin allowed algorithm
clockTolerance: 30, // 30s clock skew allowance
issuer: 'https://auth.example.com',
audience: 'api.example.com',
});
} catch (err) {
return res.status(401).json({ error: 'invalid_token' });
}
4. Fixing Preflight CORS Blocking Bearer Tokens in Browsers
Whenever JavaScript sets an Authorization header, browsers automatically trigger a preflight OPTIONS request before sending GET/POST data. Returning 401 Unauthorized on the unauthenticated OPTIONS probe blocks the actual request completely! Exempt `OPTIONS` from JWT middleware and emit explicit allowed headers (check our CORS Troubleshooting Guide).
5. Non-Negotiable JWT Verification Security Rules
- Never rely on Base64 decoding alone: Decoding payload claims via
explode('.', $jwt)[1]does zero signature verification and allows anyone to forge admin IDs! Always validate cryptographic signatures first—read our walkthrough on Decoding vs Verifying JWTs. - Pin expected
algorithmsexplicitly: Reject"alg": "none"and prevent symmetric/asymmetric key-confusion attacks by passing fixed allowed algorithms rather than trusting the unverified token header. - Validate
issandaudcleanly: Ensure staging tokens cannot replay against production endpoints even if compromised.
Browse more backend authentication and HTTP architecture guides inside our REST API & Security Hub and inspect status headers with our HTTP Status Code Lookup.
6. Rotating Signing Keys Without Breaking Active Sessions
When rotating an HS256 or RS256 signing key cleanly in zero-downtime deployments, attach a Key ID ("kid") inside the JWT protected header and keep the outgoing verification key in a secondary map until your maximum access-token TTL (for example 15 minutes) expires. That prevents sudden spikes of unexpected 401 Unauthorized logouts across logged-in users during deployment.
Frequently Asked Questions
Why does decoding my JWT work in DevTools while PHP rejects the token with 401?
Browser JWT decoders split and Base64URL-decode the header and claims without needing your secret key. A 401 happens during cryptographic verification (`HS256`/`RS256`), claim validation (`exp`/`nbf`/`iss`), or because Apache stripped the Authorization header before PHP ran.
Is increasing JWT::$leeway to 600 seconds safe?
Keep leeway minimal (15–60 seconds) alongside active NTP clock synchronization; large tolerances weaken token expiration guarantees, especially when refresh rotation revokes short-lived tokens.
Should I pass JWTs inside URL query strings (`?token=...`) to avoid Apache header issues?
No—query string tokens leak permanently into server access logs, browser histories, and external Referer headers. Fix Apache/Nginx `HTTP_AUTHORIZATION` forwarding (or use `HttpOnly; Secure; SameSite` cookies) instead.