Authentication Overview
The SSP Backend API uses JWT (JSON Web Token) authentication with role-based access control to secure all endpoints. This guide explains the authentication architecture and how it works.Authentication Architecture
The authentication system is built using:- NestJS Passport - Authentication middleware
- JWT Strategy - Token-based authentication
- bcrypt - Secure password hashing
- Guards - Route protection and authorization
Authentication Flow
How Authentication Works
1. User Login
Users authenticate by sending their username and password to/auth/login:
AuthService (defined in src/shared/auth/auth.service.ts:14) validates credentials:
2. Password Hashing
Passwords are hashed using bcrypt with a salt rounds of 10. This ensures that even if the database is compromised, passwords remain secure.3. JWT Token Generation
When credentials are valid, the API generates a JWT token containing:- sub: User ID
- rol: User role (Admin, Psicologo, TrabajoSocial, or Guia)
- nomUsuario: Username
JWT_SECRET from environment variables and has an expiration time set by JWT_EXPIRES_IN (default: 1 day).
Configuration (from src/shared/auth/auth.module.ts:18):
4. Token Validation
For subsequent requests, clients include the JWT token in theAuthorization header:
JwtStrategy (defined in src/shared/auth/jwt.strategy.ts:8) validates the token:
request.user, making it available to route handlers.
Protecting Routes
JWT Auth Guard
Protect routes by applying the@UseGuards(JwtAuthGuard) decorator:
Roles Guard
For role-based authorization, combineJwtAuthGuard with RolesGuard:
RolesGuard (from src/shared/common/guards/roles.guard.ts:9) checks if the user’s role matches:
Authentication Response
Successful login returns:Security Best Practices
Strong JWT Secrets
Use a minimum 32-character random string for
JWT_SECRET in productionToken Expiration
Set appropriate token expiration times based on security requirements (1 day is recommended)
HTTPS Only
Always use HTTPS in production to prevent token interception
Password Policies
Enforce strong password requirements and regular password changes
Configuration
Authentication is configured through environment variables:What’s Next?
JWT Tokens
Deep dive into JWT token structure and lifecycle
User Roles
Learn about the four user roles and their permissions
API Reference
See the complete login endpoint documentation
Environment Variables
Configure authentication settings
