Security Best Practices
Authentication & Authorization
JWT (JSON Web Tokens)
- All protected endpoints must use
JwtAuthGuard. - Tokens are signed with
JWT_SECRETand containuserIdandrole. - Tokens have a short lifespan (check
AuthModuleconfig), with refresh tokens for long-lived sessions.
RBAC (Role-Based Access Control)
- Do not rely solely on
isAuthenticated(). - Explicitly define required permissions for every endpoint using
@Permissions(). - Example:
@Get()
@Permissions(Permission.MANAGE_USERS) // Requires specific capability
findAll() { ... }
Data Isolation (Multi-Tenancy)
- NEVER trust the client-provided User ID in the body for data ownership checks.
- Always use the
userIdfromreq.user(injected byTenantInterceptororAuthGuard). - When using Prisma, the
TenantMiddlewareautomatically filters queries. Do not bypass this middleware (e.g., using raw SQL) without careful review.
Input Validation
- Use Zod for all DTOs (
nestjs-zod). - Strict validation prevents injection attacks and ensures data integrity.
- Sanitize inputs that will be rendered in HTML (though React handles most XSS, be careful with
innerHTML).
Rate Limiting
- Public endpoints (Login, Register) must use
RateLimitGuardor@RateLimit()decorator. - Configure limits to prevent brute-force attacks.
Audit Logging
- Critical actions (Login, Delete, Update Config) must be logged via
AuditService. - Log entries should include:
userId,action,resource,ipAddress, andstatus.
Secrets Management
- Never commit secrets to Git.
- Use
.envfiles andConfigService. - Rotate
JWT_SECRETand API keys periodically.