Token System
The authentication system uses two types of tokens:Access Token
Short-lived token for API requests. Default expiration: 15 minutes.
Refresh Token
Long-lived token for obtaining new access tokens. Default expiration: 7 days.
Authentication Flow
Middleware Protection
Theprotect middleware (from src/middlewares/auth.middleware.ts) validates JWT tokens on protected routes:
Token Payload
Access tokens contain the following claims:User ID (subject)
User role:
ADMIN, VENTANA, or VENDEDORVentana ID (for VENTANA and VENDEDOR roles)
Banca ID (for all users)
Issued at timestamp
Expiration timestamp
Environment Configuration
Configure JWT secrets and expiration in.env:
Security Features
Graceful Degradation
The auth middleware separates JWT verification from infrastructure operations (Redis/Database):- JWT errors → 401 Unauthorized
- Infrastructure errors → Retries with connection retry logic, then 500 if exhausted
Refresh Token Revocation
Refresh tokens are stored in the database and can be revoked:- On logout, the refresh token is marked as revoked
- Revoked tokens cannot be used to obtain new access tokens
- Each user can have multiple active refresh tokens (different devices)
Rate Limiting
Authentication endpoints are protected with rate limiting:Common Error Codes
| Code | Message | Cause |
|---|---|---|
| 401 | Unauthorized | Missing or invalid token |
| 401 | Invalid token | Token signature verification failed |
| 401 | Token expired | Access token has expired (use refresh) |
| 403 | Forbidden | Valid token but insufficient permissions |
| 429 | Too Many Requests | Rate limit exceeded |
Best Practices
Store tokens securely
Store tokens securely
- Never store tokens in localStorage (vulnerable to XSS)
- Use httpOnly cookies for web apps
- Use secure storage (Keychain/Keystore) for mobile apps
Handle token expiration
Handle token expiration
- Implement automatic token refresh before expiration
- Show re-authentication prompt if refresh fails
- Clear tokens and redirect to login on 401 errors
Rotate refresh tokens
Rotate refresh tokens
- Consider implementing refresh token rotation for enhanced security
- Issue a new refresh token with each refresh request
- Revoke the old refresh token after successful rotation
Related Resources
Roles & Permissions
Learn about the RBAC system
API: Login
Login endpoint reference