Auth Bypass in Nestjs
How Auth Bypass Manifests in Nestjs
Auth bypass in Nestjs applications typically occurs through several attack vectors that exploit common patterns in authentication implementation. One of the most prevalent issues is missing or improperly configured guards on route handlers. Consider this vulnerable pattern:
@Controller('users')
export class UsersController {
@Get('profile')
getUserProfile(@Request() req) {
return { id: req.user.id, email: req.user.email }; // Vulnerable if guard missing
}
}
Without an @UseGuards(AuthGuard) decorator, any unauthenticated user can access this endpoint and potentially receive undefined or default user data, leading to information disclosure or privilege escalation.
Another common Nestjs-specific auth bypass occurs with JWT strategy misconfiguration. When developers forget to validate the token audience or issuer:
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET
// Missing: audience, issuer validation
});
}
}
This allows attackers to use tokens issued for different services or with incorrect audience claims to authenticate successfully.
Role-based access control (RBAC) bypasses often occur when developers implement custom authorization logic incorrectly. A typical vulnerable pattern:
@Injectable()
export class RolesGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
const roles = ['admin'];
const user = context.switchToHttp().getRequest().user;
// Vulnerable: doesn't check if user.roles exists
return user.roles.includes(roles[0]);
}
}
If user.roles is undefined or empty, this returns false, but if roles is empty or improperly structured, it might return true unexpectedly, allowing unauthorized access.
Middleware ordering issues in Nestjs can also create auth bypass opportunities. When authentication middleware runs after route handlers:
@Controller('data')
@UseGuards(AuthGuard)
export class DataController {
@Get()
getData(@Request() req) {
return this.dataService.getData(); // Auth guard runs AFTER this
}
}
// Should be:
@Get()
@UseGuards(AuthGuard)
getData(@Request() req) {
return this.dataService.getData();
}
The placement of decorators affects execution order, potentially exposing endpoints before authentication checks occur.
Nestjs-Specific Detection
Detecting auth bypass vulnerabilities in Nestjs requires understanding both the framework's patterns and common implementation mistakes. Static analysis tools can identify missing guards and improper decorator usage:
Manual Code Review Checklist:
- Verify all sensitive endpoints have @UseGuards(AuthGuard) decorators
- Check JWT strategy configuration for audience/issuer validation
- Review custom guards for proper null/undefined checks
- Verify middleware execution order in main.ts
- Ensure role-based checks handle empty arrays and undefined values
Runtime Detection with middleBrick: middleBrick's black-box scanning approach is particularly effective for Nestjs auth bypass detection. The scanner tests unauthenticated access to endpoints that should require authentication, identifying missing guard implementations.
For example, middleBrick would detect if a Nestjs endpoint like:
@Get('admin/dashboard')
@UseGuards(RolesGuard)
getAdminDashboard() {
return { adminData: 'sensitive info' };
}
Is accessible without proper authentication by sending requests without Authorization headers and analyzing the response.
middleBrick's LLM/AI Security scanning is especially relevant for Nestjs applications using AI features. The scanner actively tests for prompt injection vulnerabilities in Nestjs endpoints that process AI requests:
@Post('chat/completions')
@UseGuards(AuthGuard)
async chatCompletion(@Body() body: { prompt: string }) {
const response = await this.openAIService.createCompletion(body.prompt);
return response;
}
middleBrick tests for system prompt leakage, instruction override attempts, and data exfiltration through the AI interface, which are Nestjs-specific concerns when using AI SDKs.
OpenAPI Spec Analysis: middleBrick analyzes Nestjs-generated OpenAPI specs to identify endpoints missing security schemes, helping detect auth bypass before deployment.
Nestjs-Specific Remediation
Remediating auth bypass in Nestjs requires leveraging the framework's built-in security features and following established patterns. Here are Nestjs-specific fixes:
Proper Guard Implementation:
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.get<string[]>('roles', context.getHandler());
if (!requiredRoles) {
return true; // No roles required
}
const user = context.switchToHttp().getRequest().user;
if (!user || !user.roles) {
return false;
}
return requiredRoles.some(role => user.roles.includes(role));
}
}
// Usage:
@Get('admin')
@UseGuards(RolesGuard)
@SetMetadata('roles', ['admin'])
getAdminData() {
return this.dataService.getAdminData();
}
Secure JWT Strategy:
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET,
audience: process.env.JWT_AUDIENCE, // Critical
issuer: process.env.JWT_ISSUER // Critical
});
}
async validate(payload: JwtPayload) {
return { userId: payload.sub, email: payload.email, roles: payload.roles };
}
}
Global Auth Configuration: Instead of decorating every controller, use a global guard in main.ts:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AuthGuard } from './auth/auth.guard';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Global auth guard - apply to all routes
app.useGlobalGuards(new AuthGuard());
// For public endpoints, use @UseGuards(AllowAnonymousGuard)
await app.listen(3000);
}
bootstrap();
Middleware Ordering: Ensure authentication runs before route handlers:
@Module({
imports: [
JwtModule.register({
secret: process.env.JWT_SECRET,
signOptions: { expiresIn: '1h' }
})
],
providers: [AuthService, JwtStrategy, RolesGuard],
exports: [AuthService, JwtStrategy, RolesGuard]
})
export class AuthModule {}
// In main.ts - order matters
app.useGlobalGuards(new JwtAuthGuard());
app.useGlobalGuards(new RolesGuard());
Testing with middleBrick: After implementing fixes, use middleBrick's CLI to verify auth controls:
npm install -g middlebrick
middlebrick scan https://your-nestjs-app.com/api
The scanner will test for unauthenticated access, missing authorization checks, and provide specific findings about auth bypass vulnerabilities in your Nestjs application.
Related CWEs: authentication
| CWE ID | Name | Severity |
|---|---|---|
| CWE-287 | Improper Authentication | CRITICAL |
| CWE-306 | Missing Authentication for Critical Function | CRITICAL |
| CWE-307 | Brute Force | HIGH |
| CWE-308 | Single-Factor Authentication | MEDIUM |
| CWE-309 | Use of Password System for Primary Authentication | MEDIUM |
| CWE-347 | Improper Verification of Cryptographic Signature | HIGH |
| CWE-384 | Session Fixation | HIGH |
| CWE-521 | Weak Password Requirements | MEDIUM |
| CWE-613 | Insufficient Session Expiration | MEDIUM |
| CWE-640 | Weak Password Recovery | HIGH |
Frequently Asked Questions
How can I test my Nestjs API for auth bypass vulnerabilities?
Use middleBrick's black-box scanning by running middlebrick scan https://your-api-url.com. The scanner tests unauthenticated access to protected endpoints, identifies missing guards, and provides specific findings with severity levels and remediation guidance. For continuous monitoring, integrate the GitHub Action into your CI/CD pipeline to automatically scan staging APIs before deployment.
Does middleBrick work with Nestjs-specific authentication patterns?
Yes, middleBrick is designed to detect auth bypass in Nestjs applications regardless of the authentication library used (Passport, JWT, custom guards). The scanner tests the actual runtime behavior of your endpoints, identifying missing @UseGuards decorators, improper JWT configuration, and role-based access control bypasses. It also includes specialized LLM security scanning for Nestjs applications using AI features.