Challenge - 5 Problems
Token Mastery in NestJS
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What is the output of this NestJS JWT token validation snippet?
Consider a NestJS service method that validates a JWT token using the JwtService. What will be the output if the token is expired?
NestJS
async validateToken(token: string) { try { const payload = this.jwtService.verify(token); return { valid: true, payload }; } catch (error) { return { valid: false, error: error.message }; } }
Attempts:
2 left
💡 Hint
Think about what happens when JwtService.verify encounters an expired token.
✗ Incorrect
The JwtService.verify method throws an error with message 'jwt expired' when the token is expired. The catch block catches this and returns an object with valid false and the error message.
📝 Syntax
intermediate1:30remaining
Which option correctly generates a JWT token with a 1 hour expiration in NestJS?
Given the JwtService instance, which code snippet correctly creates a token that expires in 1 hour?
NestJS
const payload = { username: 'user1', sub: 123 };Attempts:
2 left
💡 Hint
Check the correct option key name for expiration in JwtService.sign options.
✗ Incorrect
The correct option key is expiresIn with a string like '1h' or a number in seconds. Other keys like 'expiration' or 'expireIn' are invalid.
🔧 Debug
advanced2:00remaining
Why does this NestJS token validation code always throw an error?
Analyze the following code snippet. Why does it always throw an error when validating tokens?
NestJS
async validateToken(token: string) { const payload = this.jwtService.verify(token, { secret: 'wrongSecret' }); return payload; }
Attempts:
2 left
💡 Hint
Check the secret key used for verification compared to the signing key.
✗ Incorrect
The verify method throws a JsonWebTokenError if the secret used does not match the one used to sign the token. This causes the error.
🧠 Conceptual
advanced1:00remaining
What is the main purpose of the 'sub' claim in a JWT token?
In JWT tokens, the 'sub' claim is often included. What does it represent?
Attempts:
2 left
💡 Hint
Think about what 'sub' stands for in identity tokens.
✗ Incorrect
The 'sub' claim stands for 'subject' and identifies the principal that is the subject of the JWT, usually the user ID.
❓ state_output
expert2:30remaining
What is the value of 'isValid' after running this NestJS token validation code?
Given the following code, what will be the value of 'isValid' if the token is valid but the payload does not contain the 'sub' property?
NestJS
let isValid = false; try { const payload = this.jwtService.verify(token); if (payload.sub) { isValid = true; } } catch { isValid = false; }
Attempts:
2 left
💡 Hint
Check the condition that sets isValid to true.
✗ Incorrect
The code sets isValid to true only if payload.sub exists. If the token is valid but payload.sub is missing, isValid remains false.