-
Notifications
You must be signed in to change notification settings - Fork 0
Token Management
Azizul Hakim edited this page Nov 1, 2024
·
1 revision
The nestjs-xsecurity module uses a secure token-based system with the following features:
- Short-lived tokens (10 seconds by default)
- HMAC-SHA256 signing
- Base64 encoded payload
- Expiry timestamp validation
Each security token consists of two parts separated by a period:
base64(payload).signature
-
Payload: Base64 encoded JSON containing:
{ "expiry": 1234567890 // Unix timestamp in seconds } -
Signature: HMAC-SHA256 hash of the encoded payload using the secret key
import crypto from 'crypto';
function generateXSecurityToken(secretKey: string, expirySeconds = 10): string {
const expiryTimestamp = Math.floor(Date.now() / 1000) + expirySeconds;
const payload = { expiry: expiryTimestamp };
const token = Buffer.from(JSON.stringify(payload)).toString('base64');
const signature = crypto
.createHmac('sha256', secretKey)
.update(token)
.digest('hex');
return `${token}.${signature}`;
}graph LR
A[Generate Token] --> B[Send Request]
B --> C{Valid?}
C -->|Yes| D[Process Request]
C -->|No| E[Return 403]
E --> A
The middleware performs the following validations:
-
Format Check
const parts = token.split('.'); if (parts.length !== 2) return false;
-
Signature Verification
const [token, signature] = parts; const expectedSignature = crypto .createHmac('sha256', secretKey) .update(token) .digest('hex'); if (!crypto.timingSafeEqual( Buffer.from(expectedSignature), Buffer.from(signature) )) { return false; }
-
Expiry Validation
const payload = JSON.parse(Buffer.from(token, 'base64').toString()); if (!payload.expiry) return false; const now = Date.now() / 1000; return now < payload.expiry && payload.expiry <= now + maxExpirySeconds;
- See Configuration Options for detailed token configuration
- Check Security Best Practices for additional security measures
Copyright 2024, @AHS12 All Right Reserved