0
0
Node.jsframework~20 mins

JWT token generation and verification in Node.js - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
JWT Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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');
}
A123
BInvalid token
CSyntaxError
Dundefined
Attempts:
2 left
💡 Hint
The token is signed and verified with the same secret and is not expired.
component_behavior
intermediate
2: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);
}
ATokenExpiredError
Badmin
Cundefined
DJsonWebTokenError
Attempts:
2 left
💡 Hint
The secret used to verify must match the secret used to sign.
📝 Syntax
advanced
2: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.
Ajwt.sign({ id: 1 }, 'secret', { expiration: 7200 })
Bjwt.sign({ id: 1 }, 'secret', { expiresIn: '2h' })
Cjwt.sign({ id: 1 }, 'secret', { expireIn: 2 })
Djwt.sign({ id: 1 }, 'secret', { expires: '2hours' })
Attempts:
2 left
💡 Hint
Check the exact option name and value format for expiration in jsonwebtoken.
🔧 Debug
advanced
2: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);
AMissing secret argument in jwt.verify causes an error
BToken is expired
CPayload is empty
Djwt.sign syntax is incorrect
Attempts:
2 left
💡 Hint
jwt.verify requires the token and the secret to verify the signature.
🧠 Conceptual
expert
2: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.
AUsers will lose their passwords
BTokens will expire immediately
CAttackers can create valid tokens and impersonate users
DThe server will reject all tokens
Attempts:
2 left
💡 Hint
Think about what the secret key is used for in JWT.