0
0
NestJSframework~10 mins

JWT strategy in NestJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the JWT strategy class from Passport.

NestJS
import { [1] } from '@nestjs/passport';
Drag options to blanks, or click blank then click option'
AJwtService
BJwtModule
CJwtStrategy
DPassportStrategy
Attempts:
3 left
💡 Hint
Common Mistakes
Importing JwtStrategy directly from @nestjs/passport (it is usually a custom class).
Confusing JwtModule with PassportStrategy.
2fill in blank
medium

Complete the code to extract the JWT token from the request header.

NestJS
super({ jwtFromRequest: ExtractJwt.[1](), secretOrKey: secret });
Drag options to blanks, or click blank then click option'
AfromBodyField
BfromAuthHeaderAsBearerToken
CfromUrlQueryParameter
DfromCookie
Attempts:
3 left
💡 Hint
Common Mistakes
Using fromBodyField which expects token in the request body.
Using fromUrlQueryParameter which expects token in URL.
3fill in blank
hard

Fix the error in the validate method to correctly return the user payload.

NestJS
async validate(payload: any) {
  return [1];
}
Drag options to blanks, or click blank then click option'
Apayload.user
Bpayload.sub
Cpayload
Dpayload.id
Attempts:
3 left
💡 Hint
Common Mistakes
Returning only payload.sub which is just the user id.
Returning payload.user which may not exist.
4fill in blank
hard

Fill both blanks to correctly define the JWT strategy class extending PassportStrategy.

NestJS
export class JwtStrategy extends [1](Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.[2](),
      secretOrKey: process.env.JWT_SECRET,
    });
  }
}
Drag options to blanks, or click blank then click option'
APassportStrategy
BJwtStrategy
CfromAuthHeaderAsBearerToken
DfromBodyField
Attempts:
3 left
💡 Hint
Common Mistakes
Using JwtStrategy as base class instead of PassportStrategy.
Using fromBodyField instead of fromAuthHeaderAsBearerToken.
5fill in blank
hard

Fill all three blanks to create a validate method that returns user info from the payload.

NestJS
async validate(payload: any) {
  const user = {
    id: payload.[1],
    username: payload.[2],
    email: payload.[3]
  };
  return user;
}
Drag options to blanks, or click blank then click option'
Asub
Busername
Cemail
Did
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'id' instead of 'sub' for user id.
Mixing up username and email fields.