Skip to main content

Security Best Practices

Authentication & Authorization

JWT (JSON Web Tokens)

  • All protected endpoints must use JwtAuthGuard.
  • Tokens are signed with JWT_SECRET and contain userId and role.
  • Tokens have a short lifespan (check AuthModule config), 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 userId from req.user (injected by TenantInterceptor or AuthGuard).
  • When using Prisma, the TenantMiddleware automatically 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 RateLimitGuard or @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, and status.

Secrets Management

  • Never commit secrets to Git.
  • Use .env files and ConfigService.
  • Rotate JWT_SECRET and API keys periodically.