Challenge - 5 Problems
JWT Strategy Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What is the output when a valid JWT token is provided?
Consider a NestJS JWT strategy that validates a token and returns the user payload. What will be the result of the
validate method if the token is valid and contains { userId: 42, username: 'alice' }?NestJS
async validate(payload: any) { return { id: payload.userId, name: payload.username }; }
Attempts:
2 left
💡 Hint
The validate method transforms the JWT payload into a user object.
✗ Incorrect
The validate method receives the decoded JWT payload and returns a user object with properties renamed as id and name. So the output matches the transformed object.
📝 Syntax
intermediate2:00remaining
Which option correctly imports and uses Passport JWT strategy in NestJS?
You want to create a JWT strategy in NestJS using Passport. Which import and class extension is correct?
Attempts:
2 left
💡 Hint
NestJS wraps Passport strategies with PassportStrategy class.
✗ Incorrect
NestJS requires extending PassportStrategy with the specific Passport strategy passed as a parameter. The correct import is PassportStrategy from '@nestjs/passport' and Strategy from 'passport-jwt'.
🔧 Debug
advanced2:00remaining
Why does the JWT strategy always throw UnauthorizedException?
Given this JWT strategy code snippet, why does authentication always fail with UnauthorizedException?
class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'secretKey',
});
}
async validate(payload) {
return null;
}
}
Attempts:
2 left
💡 Hint
The validate method must return a user object or throw an exception.
✗ Incorrect
Returning null from validate signals Passport that the user is not authenticated, causing UnauthorizedException. The method should return a valid user object.
🧠 Conceptual
advanced2:00remaining
What is the purpose of the
secretOrKey option in JWT strategy?In NestJS JWT strategy configuration, what does the
secretOrKey option do?Attempts:
2 left
💡 Hint
Think about how JWT tokens are verified.
✗ Incorrect
The secretOrKey is the secret string or key used to verify the JWT token's signature to ensure it was issued by a trusted source.
❓ state_output
expert2:00remaining
What is the value of
request.user after successful JWT authentication?In a NestJS controller guarded by JwtAuthGuard, after a successful request with a valid JWT token, what will
request.user contain?Attempts:
2 left
💡 Hint
The validate method controls what user data is attached to the request.
✗ Incorrect
NestJS attaches to request.user whatever the validate method returns after verifying the JWT token.