This document covers the implementation of authentication and authorization in NestJS applications. Authentication verifies user identity (who you are), while authorization determines user permissions (what you can do). NestJS provides integrated support for both through the @nestjs/passport and @nestjs/jwt packages, implementing a guard-based security model.
This page focuses on the authentication/authorization infrastructure within the HTTP request pipeline. For information about request pipeline ordering and other cross-cutting concerns, see Guards, Interceptors, and Pipes. For middleware-based authentication approaches, see Middleware Pipeline.
Sources: sample/19-auth-jwt/package.json1-69
Authentication and authorization are implemented through Guards in NestJS, which execute after middleware but before interceptors in the request processing pipeline. Guards have access to the ExecutionContext and can determine whether a request should be handled based on authentication status and authorization rules.
The guard layer evaluates authentication tokens, validates user sessions, and enforces authorization rules before any business logic executes. Failed authentication or authorization results in an HTTP 401 (Unauthorized) or 403 (Forbidden) response without reaching the route handler.
Sources: sample/19-auth-jwt/package.json22-30
The authentication system in NestJS integrates multiple components working together to provide secure access control.
| Component | Package | Responsibility |
|---|---|---|
PassportModule | @nestjs/passport | Provides Passport.js integration and AuthGuard base class |
JwtModule | @nestjs/jwt | JWT token generation and verification |
AuthGuard | @nestjs/passport | Base guard class that delegates to Passport strategies |
Strategy | Custom implementation | Validates credentials and returns user object |
JwtService | @nestjs/jwt | Signs and verifies JWT tokens |
Sources: sample/19-auth-jwt/package.json23-26
NestJS uses the @nestjs/passport package to integrate with Passport.js, a popular authentication middleware for Node.js. The integration provides a consistent interface for implementing various authentication strategies.
Each strategy must implement a validate() method that:
The returned user object is automatically attached to the request object as request.user by Passport.
Strategies are registered as providers within authentication modules. The PassportModule must be imported to provide the necessary infrastructure.
| Strategy Type | Use Case | Validation Method |
|---|---|---|
LocalStrategy | Username/password login | Validates credentials against database |
JwtStrategy | Token-based authentication | Validates JWT signature and payload |
OAuth2Strategy | Third-party authentication | Validates OAuth tokens with provider |
| Custom strategies | Specialized requirements | Implements custom validation logic |
Sources: sample/19-auth-jwt/package.json23-26
JSON Web Tokens (JWT) provide stateless authentication by encoding user information in signed tokens. The @nestjs/jwt package provides utilities for generating and validating JWTs.
The JwtModule must be registered with configuration options:
| Configuration Option | Purpose | Example Value |
|---|---|---|
secret | Signing key for tokens | Environment variable or config |
signOptions.expiresIn | Token expiration time | '60s', '1h', '7d' |
signOptions.algorithm | Signing algorithm | 'HS256' (default), 'RS256' |
verifyOptions | Token verification options | Custom validation rules |
The JwtService provides methods:
sign(payload) - Creates a signed JWT tokenverify(token) - Validates and decodes a tokendecode(token) - Decodes without verificationSources: sample/19-auth-jwt/package.json25-26
Guards are classes that implement the CanActivate interface and determine whether a request should be processed. They execute in the guard layer of the request pipeline.
Guards can be applied at three levels:
| Application Level | Decorator Usage | Scope |
|---|---|---|
| Method-level | @UseGuards(JwtAuthGuard) on method | Single route |
| Controller-level | @UseGuards(JwtAuthGuard) on class | All routes in controller |
| Global | app.useGlobalGuards(new JwtAuthGuard()) | All routes in application |
When multiple guards are applied, they execute in order:
All guards must return true for the request to proceed. If any guard returns false or throws an exception, the request is rejected.
Sources: sample/19-auth-jwt/package.json23-26
Beyond authentication (verifying identity), authorization determines what authenticated users can access. NestJS supports several authorization patterns.
RBAC implementation requires:
@SetMetadata('roles', ['admin'])Reflector and compares with user roles| Pattern | Implementation | Use Case |
|---|---|---|
| Role-Based (RBAC) | Compare user roles to required roles | Simple permission systems |
| Attribute-Based (ABAC) | Evaluate user attributes and context | Complex policies |
| Ownership | Check if user owns the resource | User-specific data access |
| Permission-Based | Check specific permissions | Fine-grained control |
Sources: sample/19-auth-jwt/package.json23-26
Authentication modules follow NestJS's dynamic module pattern, allowing configuration at import time.
The AuthModule typically imports and configures:
| Module Import | Configuration | Purpose |
|---|---|---|
PassportModule.register({...}) | defaultStrategy: 'jwt' | Configures default authentication strategy |
JwtModule.register({...}) | secret, signOptions | Configures JWT generation and validation |
UsersModule | N/A | Provides user lookup and validation |
The authentication module exports strategies and services that other modules can use by importing AuthModule.
JWT module configuration supports:
| Option | Type | Description |
|---|---|---|
secret | string | Signing secret (should be from environment) |
publicKey / privateKey | `string | Buffer` |
signOptions.expiresIn | `string | number` |
signOptions.issuer | string | Token issuer claim |
signOptions.audience | string | Token audience claim |
verifyOptions | VerifyOptions | Custom verification options |
Sources: sample/19-auth-jwt/package.json1-69
The authentication sample application demonstrates a complete JWT-based authentication implementation.
The sample includes:
The authentication sample requires these packages:
| Package | Version | Purpose |
|---|---|---|
@nestjs/passport | 11.0.5 | Passport.js integration |
@nestjs/jwt | 11.0.2 | JWT token handling |
passport-local | (peer dependency) | Local username/password strategy |
passport-jwt | (peer dependency) | JWT token strategy |
Sources: sample/19-auth-jwt/package.json1-69
Authentication integrates with various NestJS features for comprehensive application security.
| Feature | Integration Point | Purpose |
|---|---|---|
| Swagger (API Docs) | @ApiBearerAuth() decorator | Documents authentication requirements |
| GraphQL | Context resolver | Attaches user to GraphQL context |
| WebSockets | Custom gateway guards | Secures WebSocket connections |
| Microservices | Custom transport guards | Authenticates service-to-service calls |
| Serialization | @Exclude() decorator | Removes sensitive fields from responses |
Authentication components can be tested using @nestjs/testing:
| Test Type | Approach | Tools |
|---|---|---|
| Unit tests | Mock JwtService and strategies | Jest mocks |
| Integration tests | Test actual authentication flow | supertest for HTTP requests |
| E2E tests | Full authentication with database | Test database setup |
The testing module provides utilities to override authentication guards during testing, allowing tests to bypass authentication or test specific user scenarios.
Sources: sample/19-auth-jwt/package.json1-69
Refresh this wiki