All skills
Skillintermediate
Authentication & Guards
```typescript // jwt.strategy.ts import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
Claude Code Knowledge Pack7/10/2026
Overview
Authentication & Guards
JWT Strategy
// jwt.strategy.ts
@Injectable()
constructor(private config: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: config.get('JWT_SECRET'),
});
}
async validate(payload: { sub: string; email: string; role: string }) {
return { userId: payload.sub, email: payload.email, role: payload.role };
}
}
JWT Auth Guard
// jwt-auth.guard.ts
@Injectable()
constructor(private reflector: Reflector) {
super();
}
canActivate(context: ExecutionContext) {
const isPublic = this.reflector.get<boolean>('isPublic', context.getHandler());
if (isPublic) return true;
return super.canActivate(context);
}
handleRequest(err: any, user: any) {
if (err || !user) {
throw err || new UnauthorizedException('Invalid token');
}
return user;
}
}
// Public decorator
Roles Guard
// roles.decorator.ts
// roles.guard.ts
@Injectable()
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.getAllAndOverride<string[]>('roles', [
context.getHandler(),
context.getClass(),
]);
if (!roles) return true;
const { user } = context.switchToHttp().getRequest();
return roles.includes(user.role);
}
}
// Usage
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin')
@Get('admin')
adminEndpoint() {}
Auth Service
@Injectable()
constructor(
private usersService: UsersService,
private jwtService: JwtService,
) {}
async validateUser(email: string, password: string): Promise {
const user = await this.usersService.findByEmail(email);
if (user && await bcrypt.compare(password, user.password)) {
return user;
}
return null;
}
async login(user: User) {
const payload = { sub: user.id, email: user.email, role: user.role };
return {
access_token: this.jwtService.sign(payload),
refresh_token: this.jwtService.sign(payload, { expiresIn: '7d' }),
};
}
async register(dto: CreateUserDto) {
const hashedPassword = await bcrypt.hash(dto.password, 10);
return this.usersService.create({ ...dto, password: hashedPassword });
}
}
Auth Module Setup
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
secret: config.get('JWT_SECRET'),
signOptions: { expiresIn: '15m' },
}),
}),
UsersModule,
],
providers: [AuthService, JwtStrategy],
exports: [AuthService],
})
Apply Guards Globally
// app.module.ts
@Module({
providers: [
{ provide: APP_GUARD, useClass: JwtAuthGuard },
{ provide: APP_GUARD, useClass: RolesGuard },
],
})
Quick Reference
| Component | Purpose |
|---|---|
JwtStrategy | Validate JWT tokens |
JwtAuthGuard | Protect routes |
RolesGuard | Role-based access |
@Public() | Skip auth |
@Roles('admin') | Require role |
@UseGuards() | Apply guard |