Authentication confirms who the user is. In NestJS APIs, it ensures only verified users can access protected routes.
Without valid authentication, NestJS APIs respond with a 401 error to prevent unauthorized access.
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
if (!request.user) {
throw new UnauthorizedException('User not authenticated');
}
return true;
}
What will the API respond with if the request has no user?canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
if (!request.user) {
throw new UnauthorizedException('User not authenticated');
}
return true;
}The guard throws an UnauthorizedException which results in a 401 response with the given message.
Option A correctly uses AuthGuard with the 'jwt' strategy to protect the route.
Option A is missing the AuthGuard function call.
Option A lacks the strategy name.
Option A uses 'local' strategy which is not for JWT authentication.
@Controller('data')
export class DataController {
@Get()
@UseGuards(AuthGuard('jwt'))
getData() {
return 'Protected data';
}
@Get('public')
getPublicData() {
return 'Public data';
}
}
A user can access the 'getData' route without a token. What is the most likely reason?@Controller('data') export class DataController { @Get() @UseGuards(AuthGuard('jwt')) getData() { return 'Protected data'; } @Get('public') getPublicData() { return 'Public data'; } }
If the AuthGuard is not properly registered or the JWT strategy is not configured, the guard will not block unauthenticated requests even if used.
