JWT Tokens
JSON Web Tokens (JWT) are the primary authentication mechanism in the SSP Backend API. This guide explains how JWT tokens work, their structure, and how to use them effectively.What is a JWT?
A JWT is a compact, URL-safe token that contains encoded JSON data. It consists of three parts separated by dots:Token Structure
Header
Contains metadata about the token:- alg: Algorithm used for signing (HMAC SHA256)
- typ: Token type (JWT)
Payload
Contains the claims (user data):- sub (Subject): User ID - the unique identifier for the user
- rol (Role): User role - one of
Admin,Psicologo,TrabajoSocial, orGuia - nomUsuario: Username used for login
- iat (Issued At): Timestamp when the token was created
- exp (Expiration): Timestamp when the token expires
Signature
The signature ensures the token hasn’t been tampered with. It’s created by:JWT_SECRET from your environment variables is used to sign and verify tokens.
Token Generation
Tokens are generated during the login process. Here’s how it works insrc/shared/auth/auth.service.ts:25:
JWT Configuration
JWT settings are configured insrc/shared/auth/auth.module.ts:16:
Token Expiration
Default Expiration
By default, tokens expire after 1 day (24 hours). This is controlled by theJWT_EXPIRES_IN environment variable.
Configuring Expiration
You can customize the expiration time in your.env file:
When Tokens Expire
When a token expires:- The API rejects the request with a 401 Unauthorized error
- The client must request a new token by logging in again
- There is currently no refresh token mechanism (re-login required)
Using JWT Tokens
Making Authenticated Requests
Include the JWT token in theAuthorization header with the Bearer scheme:
In Different HTTP Clients
Token Validation
TheJwtStrategy automatically validates tokens on protected routes (from src/shared/auth/jwt.strategy.ts:8):
Validation Process
Extract Token
The token is extracted from the
Authorization header using ExtractJwt.fromAuthHeaderAsBearerToken()Verify Signature
The token signature is verified using the
JWT_SECRET to ensure it hasn’t been tampered withCheck Expiration
The token’s expiration time (
exp claim) is checked. If expired, the request is rejected.Token Lifecycle
Security Considerations
JWT Secret
TheJWT_SECRET is critical for security:
Generate a secure secret:
Token Storage (Client-Side)
Recommended: Memory
Store tokens in application memory for maximum security (lost on page refresh)
SessionStorage
Cleared when tab closes, safer than localStorage
LocalStorage
Persistent but vulnerable to XSS attacks - use with caution
HTTP-Only Cookies
Most secure option but requires server-side implementation changes
Common Vulnerabilities
Token Theft (Man-in-the-Middle)
Token Theft (Man-in-the-Middle)
Mitigation: Always use HTTPS in production to encrypt tokens in transit.
XSS (Cross-Site Scripting)
XSS (Cross-Site Scripting)
Mitigation:
- Sanitize all user inputs
- Use Content Security Policy (CSP) headers
- Avoid storing tokens in localStorage if possible
- Use HTTP-only cookies for token storage
Token Replay Attacks
Token Replay Attacks
Mitigation:
- Use short expiration times
- Implement token refresh mechanisms
- Consider adding IP address or user agent to token claims
- Log and monitor for suspicious token usage patterns
Debugging Tokens
Decode JWT Tokens
You can decode (but not verify) tokens at jwt.io to inspect their contents.Note: jwt.io is safe for decoding tokens during development, but never paste production tokens into third-party tools. Use local tools instead.
Local Decoding
Decode tokens locally using Node.js:Future Enhancements
The current implementation could be enhanced with:- Refresh Tokens: Long-lived tokens for obtaining new access tokens without re-login
- Token Revocation: Blacklist mechanism for invalidating tokens before expiration
- Multiple Token Types: Separate tokens for different scopes (admin actions, API access, etc.)
- Token Rotation: Automatic token refresh on activity
What’s Next?
User Roles
Learn about role-based access control and permissions
Authentication Overview
Understanding the complete authentication flow
Environment Variables
Configure JWT settings and secrets
API Reference
Complete login endpoint documentation
