Fix BFLA (Broken Function Level Authorization) in NestJS
BFLA (Broken Function Level Authorization) is the silent killer of enterprise APIs. It occurs when an application relies on 'security through obscurity' or fails to verify if a user has the specific permission to execute a function, even if they are authenticated. In NestJS, this usually manifests as missing Guards or improper Reflector usage on sensitive administrative endpoints.
The Vulnerable Pattern
@Controller('admin') @UseGuards(JwtAuthGuard) export class AdminController { constructor(private readonly userService: UserService) {}
@Delete(‘user/:id’) // VULNERABILITY: Only checks if user is logged in (JWT), not if they are an Admin. // Any authenticated user can delete any other user. async deleteUser(@Param(‘id’) id: string) { return this.userService.remove(id); } }
The Secure Implementation
To kill BFLA in NestJS, you must implement a multi-layered defense. First, create a custom @Roles() decorator to attach metadata to specific routes. Second, implement a RolesGuard that utilizes the NestJS Reflector to compare the user's JWT payload roles against the route requirements. Finally, apply the guard either globally in main.ts or at the controller level. For complex scenarios, integrate CASL for Attribute-Based Access Control (ABAC) to ensure users can only perform functions on resources they own.
// 1. Define Roles Decorator export const Roles = (...roles: string[]) => SetMetadata('roles', roles);// 2. Implement RolesGuard @Injectable() export class RolesGuard implements CanActivate { constructor(private reflector: Reflector) {} canActivate(context: ExecutionContext): boolean { const requiredRoles = this.reflector.getAllAndOverride<string[]>(‘roles’, [ context.getHandler(), context.getClass(), ]); if (!requiredRoles) return true; const { user } = context.switchToHttp().getRequest(); return requiredRoles.some((role) => user.roles?.includes(role)); } }
// 3. Secure Controller @Controller(‘admin’) @UseGuards(JwtAuthGuard, RolesGuard) export class AdminController { @Delete(‘user/:id’) @Roles(‘admin’) // ENFORCEMENT: Only users with ‘admin’ role can pass async deleteUser(@Param(‘id’) id: string) { return this.userService.remove(id); } }
Your NestJS API
might be exposed to BFLA (Broken Function Level Authorization)
74% of NestJS apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.