Chapter 6: Authentication & Authorization
Securing your application is critical. This chapter covers authentication (verifying identity), authorization (controlling access), JWT, OAuth, RBAC, password hashing, guards, and best practices for building secure APIs in NestJS. We’ll walk through practical examples and explain the “why” behind each step.
6.1 Authentication vs Authorization
Understanding the difference between authentication and authorization is fundamental to building secure applications.Authentication
Authentication answers: “Who are you?”- Verifies user identity
- Confirms credentials (username/password, token, etc.)
- Establishes user session
- Examples: Login, token validation
Authorization
Authorization answers: “What are you allowed to do?”- Controls access to resources
- Enforces permissions and roles
- Determines what actions are allowed
- Examples: Admin-only routes, resource ownership checks
Think of authentication as showing your ID at the door (proving who you are), and authorization as checking if you’re allowed into the VIP section (what you can access).
The Relationship
6.2 Password Hashing
Before implementing authentication, you must understand password security. Never store passwords in plain text.Why Hash Passwords?
- Security: Even if database is compromised, passwords are protected
- Privacy: Developers can’t see user passwords
- Compliance: Required by security standards (GDPR, PCI-DSS)
Using bcrypt
Password Validation
6.3 JWT Authentication
JSON Web Tokens (JWT) are a popular way to implement stateless authentication in APIs. JWTs are signed tokens that clients send with each request to prove their identity.How JWT Works
- User logs in with credentials
- Server validates credentials
- Server creates and signs a JWT
- Client stores the JWT
- Client sends JWT in
Authorizationheader - Server verifies JWT and extracts user info
Installing JWT Package
JWT Module Setup
Auth Service
JWT Strategy
Local Strategy (Username/Password)
Auth Controller
JWT Auth Guard
Local Auth Guard
Using JWT Guard
6.4 Authorization: Roles & Permissions
Role-Based Access Control (RBAC) restricts access based on user roles. This lets you control who can do what in your app.Roles Decorator
Roles Guard
Using Roles
Permission-Based Authorization
For more granular control, use permissions:6.5 OAuth2 & Social Login
NestJS supports OAuth2 via Passport strategies. This lets users log in with Google, Facebook, GitHub, etc.Installing Passport OAuth
Google Strategy
Google Auth Controller
6.6 Refresh Tokens
Refresh tokens allow users to get new access tokens without re-authenticating.Implementing Refresh Tokens
6.7 Multi-Factor Authentication (MFA)
Enhance security by requiring a second factor (e.g., OTP, email code) after password login.MFA Service
6.8 Security Best Practices
Following security best practices protects your application and users.Password Security
- Always hash passwords (use bcrypt with salt rounds >= 10)
- Enforce strong password policies
- Never log or return passwords
- Use password reset tokens (time-limited)
JWT Security
- Use strong, random secrets
- Set appropriate expiration times
- Use HTTPS in production
- Store secrets in environment variables
- Consider refresh tokens for long sessions
HTTP Security Headers
Rate Limiting
CORS Configuration
Input Validation
Always validate and sanitize input:Security Checklist
- Always hash passwords
- Use HTTPS in production
- Store secrets in environment variables
- Set secure HTTP headers (helmet)
- Limit login attempts (prevent brute force)
- Validate and sanitize all input
- Keep dependencies up to date
- Use CORS to restrict allowed origins
- Log authentication events for auditing
- Implement rate limiting
- Use refresh tokens for long sessions
- Consider MFA for sensitive applications
6.9 Real-World Example: Complete Auth Module
Here’s a complete authentication module structure:6.10 Summary
You’ve learned how to secure your NestJS APIs: Key Concepts:- Authentication: Verifying user identity
- Authorization: Controlling access to resources
- JWT: Stateless token-based authentication
- OAuth2: Social login integration
- RBAC: Role-based access control
- Password Hashing: Secure password storage
- MFA: Multi-factor authentication
- Always hash passwords
- Use HTTPS in production
- Store secrets in environment variables
- Set secure HTTP headers
- Implement rate limiting
- Validate all input
- Use refresh tokens
- Log authentication events