Mastering JWT: Structure, Renewal Strategies, and PHP Implementation
This guide explains the JWT format, standard and custom claims, signature algorithms, and presents practical single‑token and double‑token renewal schemes—including a WeChat OAuth example—along with a complete PHP implementation using the tinywan/jwt library.
What is JWT?
JSON Web Token (JWT) is an open standard (RFC 7519) for securely transmitting claims between parties. It defines a token‑based session model without prescribing a specific implementation, making it suitable for distributed single sign‑on (SSO) scenarios.
JWT Structure
A JWT consists of three Base64‑URL‑encoded parts separated by dots: header, payload, and signature.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cHeader – specifies the signing algorithm and token type.
Payload – a JSON object containing claims.
Signature – protects the token from tampering.
Standard Claims (Payload)
iss (issuer) : token issuer
exp (expiration) : expiration time
sub (subject) : subject identifier
aud (audience) : intended audience
nbf (not before) : time before which the token is invalid
iat (issued at) : issuance timestamp
jti (JWT ID) : unique identifierDevelopers may add custom claims, but because JWTs are not encrypted by default, secret data should never be placed in the payload.
Token Expiration and Renewal
When a token expires, the client must obtain a new one. Two common renewal patterns are described below.
Single‑Token Scheme
Set a short TTL (e.g., 15 minutes) for the token.
The client sends a request; the backend checks expiration.
If expired, the client requests a refresh and the backend issues a new token.
Optionally enforce a forced re‑login after a fixed period (e.g., 72 hours) by tracking the last login timestamp.
The backend may limit the number of refreshes (e.g., max 50).
Double‑Token Scheme
Upon login, the backend returns an access_token (short‑lived) and a refresh_token (long‑lived).
The client uses the access_token for API calls; when it expires, the client sends the refresh_token to obtain a new access_token.
The backend validates the refresh_token expiration before issuing a new access_token.
Logout or password change invalidates both tokens.
WeChat OAuth 2.0 Example
User authorizes via WeChat and receives a short‑lived access_token (2 hours) and a long‑lived refresh_token (30 days).
When the access_token expires, the client refreshes it using the refresh_token.
If the refresh_token expires, the user must re‑authorize.
Backends often store tokens in Redis with an expiration key to detect expired tokens efficiently.
Practical PHP Implementation
Install the JWT library via Composer: composer require tinywan/jwt Generate a token:
$user = [
'id' => 2022, // globally unique identifier
'name' => 'Tinywan',
'email' => '[email protected]'
];
$token = Tinywan\Jwt\JwtToken::generateToken($user);
var_dump(json_encode($token));Typical JSON response:
{
"token_type": "Bearer",
"expires_in": 36000,
"access_token": "eyJ0eXAiOiJAUR‑Gqtnk9LUPO8IDrLK7tjCwQZ7CI...",
"refresh_token": "eyJ0eXAiOiJIEGkKprvcccccQvsTJaOyNy8yweZc..."
}Signature Algorithms
Common JWT signing algorithms (JWA) include HS256 (HMAC‑SHA256), RS256 (RSA‑SHA256), and ES256 (ECDSA‑SHA256).
+------+---------------------------+--------------------+
| "alg"| Digital Signature or MAC | Implementation |
+------+---------------------------+--------------------+
| HS256| HMAC using SHA‑256 | Required |
| RS256| RSASSA‑PKCS1‑v1_5 using SHA‑256 | Recommended |
| ES256| ECDSA using P‑256 + SHA‑256 | Recommended |
+------+---------------------------+--------------------+HS256 uses a shared secret; leakage of the secret compromises security, so it is appropriate only for centralized authentication. RS256 and ES256 use asymmetric keys: the private key signs, the public key verifies, allowing multiple services to validate tokens without exposing the private key.
Algorithm List
+--------------+-------------------------------+--------------------+
| "alg" Param | Digital Signature or MAC | Implementation |
+--------------+-------------------------------+--------------------+
| HS256 | HMAC using SHA‑256 | Required |
| HS384 | HMAC using SHA‑384 | Optional |
| HS512 | HMAC using SHA‑512 | Optional |
| RS256 | RSASSA‑PKCS1‑v1_5 using SHA‑256| Recommended |
| RS384 | RSASSA‑PKCS1‑v1_5 using SHA‑384| Optional |
| RS512 | RSASSA‑PKCS1‑v1_5 using SHA‑512| Optional |
| ES256 | ECDSA using P‑256 + SHA‑256 | Recommended |
| ES384 | ECDSA using P‑384 + SHA‑384 | Optional |
| ES512 | ECDSA using P‑521 + SHA‑512 | Optional |
| PS256 | RSASSA‑PSS using SHA‑256 + MGF1| Optional |
| PS384 | RSASSA‑PSS using SHA‑384 + MGF1| Optional |
| PS512 | RSASSA‑PSS using SHA‑512 + MGF1| Optional |
| none | No digital signature or MAC | Optional |
+--------------+-------------------------------+--------------------+Symmetric Algorithms
HS256 signs and verifies with the same secret_key. If the secret leaks, security is lost, so HS256 is best suited for environments where a trusted party controls both signing and verification.
Asymmetric Algorithms
RS256 signs with an RSA private key and verifies with the corresponding public key. The public key can be freely distributed; only the private key must remain confidential. This enables token verification by multiple services without sharing secret material.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
