JWT Strategies & RBAC

Preview — 3 of 10 questions

Why does a NestJS JWT strategy class extend PassportStrategy(Strategy) rather than Strategy directly?

javascript
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: process.env.JWT_SECRET!,
    });
  }
  async validate(payload: { sub: string }): Promise<{ id: string }> {
    return { id: payload.sub };
  }
}
ATo bypass Passport entirely
BBecause Strategy is abstract and cannot be extended
CPassportStrategy is a mixin that adapts the raw passport-jwt Strategy into an injectable, DI-managed provider and auto-registers it
DTo enable CORS

What exactly does ExtractJwt.fromAuthHeaderAsBearerToken() return when configured as jwtFromRequest?

javascript
super({
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  ignoreExpiration: false,
  secretOrKey: process.env.JWT_SECRET!,
});
AThe decoded JWT payload
BA function that extracts the raw token string from the Authorization: Bearer header for each request
CThe signing secret
DA boolean indicating if the header exists

What is the purpose of secretOrKey in the JWT strategy options?

javascript
super({
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: process.env.JWT_SECRET!, // must equal the signing secret for HS256
  algorithms: ['HS256'],
});
AIt supplies the symmetric secret (or public key) used to verify the token signature
BIt is the username field name
CIt sets the token expiration
DIt defines the cookie name

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.