Overview
TheJwtAuthService is a singleton service that handles JWT token generation, validation, encryption, and refresh token management. It uses HS256 algorithm for signing tokens and stores refresh tokens securely in the database.
This is a singleton service. Always use
JwtAuthService::getInstance() to access it.Getting Instance
getInstance()
Retrieves the singleton instance of JwtAuthService.Example
Methods
generateTokens()
Generates both access and refresh JWT tokens for a user.The user’s unique identifier
The user’s name to include in the token payload
JWT access token (expires in 30 seconds)
JWT refresh token (expires in 7 days)
Example
Behavior
- Creates access token with payload:
{id, name, exp} - Creates refresh token with payload:
{id, exp} - Access token expires in 30 seconds (configured in
$accessTokenExpiry) - Refresh token expires in 604800 seconds / 7 days (configured in
$refreshTokenExpiry) - Stores hashed refresh token in
refresh_tokensdatabase table - Sets refresh token in HTTP-only cookie
- Returns both tokens
JwtEncrypt()
Encrypts a payload into a JWT token.The data to encode in the JWT token
Encoded JWT token string
Example
Algorithm
- Base64 URL-encodes the header:
{"alg":"HS256","type":"JWT"} - Base64 URL-encodes the payload
- Creates signature using HMAC SHA256 with secret key
- Returns token format:
header.payload.signature
JwtValidate()
Validates a JWT token and returns the decoded payload.The JWT token to validate
Returns decoded payload array if valid,
false if invalid or expiredExample
Validation Steps
- Splits token into header, payload, and signature
- Decodes header and payload from Base64
- Checks expiration time against current time
- Verifies signature using HMAC SHA256
- Returns decoded payload if all checks pass
- Returns
falseif token is invalid, expired, or malformed
refreshToken()
Refreshes an expired access token using a valid refresh token from cookies.HTTP status code (200 for success, 401 for failure)
New tokens object
Example
Behavior
- Retrieves refresh token from
user_tokencookie - Validates refresh token structure and expiration
- Verifies refresh token exists in database (checks against hashed value)
- Generates new access and refresh tokens
- Returns Response object with status 200 and new tokens
- Returns Response with status 401 if refresh token is missing, invalid, or not found in database
regenerateJwt()
Regenerates a new access token from an existing valid token.The existing JWT token to regenerate from
HTTP status code (200 for success, 401 for failure)
New JWT token
Example
revokeRefreshToken()
Revokes a user’s refresh token (typically used during logout).The user ID whose refresh token should be revoked
HTTP status code (200 for success)
Success message: “Refresh token revoked”
Example
Behavior
- Deletes refresh token from
refresh_tokenstable for the specified user - Clears the
user_tokencookie - Returns success response
Configuration
Token Expiration Times
JWT Header
Cookie Configuration
Refresh tokens are stored in cookies with:- Name:
user_token - Expiration: 7 days
- Path:
/ - Secure:
true(HTTPS only) - HttpOnly:
true(not accessible via JavaScript) - SameSite:
None - Domain:
.localhost.com
Database Schema
The service expects arefresh_tokens table with the following structure:
Security Features
- Token Signing: Uses HMAC SHA256 for token signatures
- Refresh Token Hashing: Refresh tokens are stored as bcrypt hashes in database
- Token Expiration: Both access and refresh tokens have expiration timestamps
- Secure Cookies: HTTP-only, secure cookies prevent XSS attacks
- Token Rotation: Each refresh generates new access and refresh tokens
- Single Session: Only one refresh token per user (old tokens are deleted)
Source Reference
Location:~/workspace/source/Sphp/Services/JwtAuthService.php