NestJS Authentication Flow

Client Request
     │
     ▼
Guard (JwtAuthGuard)
     │
     ▼
AuthGuard('jwt')
     │
     ▼
Passport Strategy (JwtStrategy)
     │
     ▼
validate()
     │
     ▼
req.user attached
     │
     ▼
Controller

Components

Component Responsibility
Strategy How credentials are validated
Guard Whether request is allowed to continue
Decorator Attach metadata to routes/classes
Reflector Read metadata at runtime
Controller Handle request & call services

Example:

auth
 ├── strategies
 │     ├── jwt.strategy.ts
 │     └── jwt-refresh.strategy.ts
 │
 ├── guards
 │     ├── jwt-auth.guard.ts
 │     ├── jwt-refresh.guard.ts
 │     └── roles.guard.ts
 │
 ├── decorators
 │     ├── public.decorator.ts
 │     └── roles.decorator.ts

Strategy

jwt strategy
google oauth strategy
facebook strategy
local username/password strategy

JWT Strategy

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor(config: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: config.get('JWT_SECRET'),
    });
  }

  async validate(payload: any) {
    return {
      userId: payload.sub,
      email: payload.email,
      roles: payload.roles,
    };
  }
}