Challenge - 5 Problems
JWT Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this JWT token verification code?
Consider this Node.js code using the jsonwebtoken library. What will be logged to the console?
Node.js
import jwt from 'jsonwebtoken'; const secret = 'mysecret'; const token = jwt.sign({ userId: 123 }, secret, { expiresIn: '1h' }); try { const decoded = jwt.verify(token, secret); console.log(decoded.userId); } catch (err) { console.log('Invalid token'); }
Attempts:
2 left
💡 Hint
The token is signed and verified with the same secret and is not expired.
✗ Incorrect
The token is correctly signed with the secret and verified immediately, so the payload is decoded and userId 123 is logged.
❓ component_behavior
intermediate2:00remaining
What happens if you verify a JWT token with the wrong secret?
Given this code snippet, what will be the console output?
Node.js
import jwt from 'jsonwebtoken'; const secret = 'correctsecret'; const wrongSecret = 'wrongsecret'; const token = jwt.sign({ role: 'admin' }, secret); try { const decoded = jwt.verify(token, wrongSecret); console.log(decoded.role); } catch (error) { console.log(error.name); }
Attempts:
2 left
💡 Hint
The secret used to verify must match the secret used to sign.
✗ Incorrect
Verifying a token with a different secret than the one used to sign it causes a JsonWebTokenError because the signature does not match.
📝 Syntax
advanced2:00remaining
Which option correctly generates a JWT token with an expiration of 2 hours?
Choose the code snippet that correctly creates a JWT token with a 2-hour expiration using jsonwebtoken.
Attempts:
2 left
💡 Hint
Check the exact option name and value format for expiration in jsonwebtoken.
✗ Incorrect
The correct option uses the 'expiresIn' option with a string '2h' to set expiration to 2 hours. Other options use incorrect property names or formats.
🔧 Debug
advanced2:00remaining
Why does this JWT verification code throw an error?
Examine the code and select the reason for the error thrown during verification.
Node.js
import jwt from 'jsonwebtoken'; const secret = 'topsecret'; const token = jwt.sign({ name: 'Alice' }, secret); const decoded = jwt.verify(token); console.log(decoded.name);
Attempts:
2 left
💡 Hint
jwt.verify requires the token and the secret to verify the signature.
✗ Incorrect
jwt.verify requires both the token and the secret key to verify the token's signature. Omitting the secret causes an error.
🧠 Conceptual
expert2:00remaining
What is the main security risk if you expose your JWT secret key publicly?
Select the best explanation for the risk of exposing your JWT secret key.
Attempts:
2 left
💡 Hint
Think about what the secret key is used for in JWT.
✗ Incorrect
The secret key signs tokens. If attackers get it, they can create tokens that the server accepts as valid, allowing impersonation.