Bird
Raised Fist0
NestJSframework~20 mins

Token generation and validation in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Token Mastery in NestJS
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2: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 };
  }
}
AThrows an unhandled exception
B{ valid: true, payload: <decoded_payload> }
C{ valid: false, error: 'invalid token' }
D{ valid: false, error: 'jwt expired' }
Attempts:
2 left
💡 Hint
Think about what happens when JwtService.verify encounters an expired token.
📝 Syntax
intermediate
1: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 };
Athis.jwtService.sign(payload, { expiresIn: '1h' });
Bthis.jwtService.sign(payload, { expiration: 3600 });
Cthis.jwtService.sign(payload, { expires: 3600 });
Dthis.jwtService.sign(payload, { expireIn: '1h' });
Attempts:
2 left
💡 Hint
Check the correct option key name for expiration in JwtService.sign options.
🔧 Debug
advanced
2: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;
}
ABecause the secret used to verify the token is incorrect, causing a JsonWebTokenError.
BBecause the token is expired and no catch block handles the error.
CBecause the token is malformed and cannot be parsed.
DBecause the method is missing async/await keywords.
Attempts:
2 left
💡 Hint
Check the secret key used for verification compared to the signing key.
🧠 Conceptual
advanced
1: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?
AIt contains the token's signature algorithm.
BIt specifies the token's expiration time.
CIt identifies the subject or user the token is issued for.
DIt indicates the token issuer's name.
Attempts:
2 left
💡 Hint
Think about what 'sub' stands for in identity tokens.
❓ state_output
expert
2: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;
}
Atrue
Bfalse
CThrows an error
Dundefined
Attempts:
2 left
💡 Hint
Check the condition that sets isValid to true.

Practice

(1/5)
1. What is the main purpose of generating a token in a NestJS application?
easy
A. To prove a user's identity without sharing their password
B. To store user passwords securely
C. To encrypt the entire database
D. To create a backup of user data

Solution

  1. Step 1: Understand token purpose

    Tokens are used to prove who a user is without sharing sensitive information like passwords.
  2. Step 2: Compare options

    Only To prove a user's identity without sharing their password correctly describes token use; others describe unrelated tasks.
  3. Final Answer:

    To prove a user's identity without sharing their password -> Option A
  4. Quick Check:

    Token purpose = Identity proof without password [OK]
Hint: Tokens prove identity safely without passwords [OK]
Common Mistakes:
  • Thinking tokens store passwords
  • Confusing tokens with database encryption
  • Assuming tokens backup data
2. Which of the following is the correct way to generate a JWT token using the jsonwebtoken package in NestJS?
easy
A. jwt.sign(payload, secretKey, { expiresIn: '1h' })
B. jwt.create(payload, secretKey)
C. jwt.generateToken(secretKey, payload)
D. jwt.verify(payload, secretKey)

Solution

  1. Step 1: Recall JWT token creation syntax

    The sign method creates a token with payload, secret key, and options.
  2. Step 2: Check options

    Only jwt.sign(payload, secretKey, { expiresIn: '1h' }) uses sign correctly with payload, secret, and expiration.
  3. Final Answer:

    jwt.sign(payload, secretKey, { expiresIn: '1h' }) -> Option A
  4. Quick Check:

    Token creation uses sign() method [OK]
Hint: Use jwt.sign() to create tokens with payload and secret [OK]
Common Mistakes:
  • Using jwt.create() which does not exist
  • Mixing order of arguments
  • Using jwt.verify() to create tokens
3. Given the following code snippet in a NestJS service, what will be the output if the token is valid?
const token = jwt.sign({ userId: 123 }, 'secretKey', { expiresIn: '1h' });
const decoded = jwt.verify(token, 'secretKey');
console.log(decoded.userId);
medium
A. undefined
B. null
C. 123
D. Throws an error

Solution

  1. Step 1: Understand token creation and verification

    The token is created with payload { userId: 123 } and signed with 'secretKey'.
  2. Step 2: Verify token with the same secret

    Verification returns the decoded payload, so decoded.userId is 123.
  3. Final Answer:

    123 -> Option C
  4. Quick Check:

    Valid token returns payload userId = 123 [OK]
Hint: Verify returns original payload if token and secret match [OK]
Common Mistakes:
  • Expecting undefined or null instead of payload
  • Using wrong secret causing error
  • Confusing verify with sign
4. Identify the error in this NestJS token validation code:
try {
  const payload = jwt.verify(token, secret);
  return payload.userId;
} catch (error) {
  return 'Invalid token';
}
medium
A. Secret key is not defined
B. Missing async keyword for jwt.verify
C. jwt.verify should be jwt.sign
D. No error, code works correctly

Solution

  1. Step 1: Analyze jwt.verify usage

    jwt.verify is synchronous and used correctly inside try-catch to handle errors.
  2. Step 2: Check for missing elements

    Assuming secret and token are defined, no syntax or logic errors exist.
  3. Final Answer:

    No error, code works correctly -> Option D
  4. Quick Check:

    jwt.verify with try-catch is correct pattern [OK]
Hint: jwt.verify is synchronous; use try-catch for errors [OK]
Common Mistakes:
  • Thinking jwt.verify is async
  • Confusing verify with sign
  • Assuming secret is undefined without context
5. You want to generate a JWT token in NestJS that expires in 30 minutes and includes the user's email and role. Which code snippet correctly achieves this?
hard
A. jwt.sign({ email, role }, secretKey, { expiresAt: '30m' })
B. jwt.sign({ email, role }, secretKey, { expiresIn: '30m' })
C. jwt.sign({ email, role }, secretKey, { expiration: 1800 })
D. jwt.sign({ email, role }, secretKey, { expireIn: 30 })

Solution

  1. Step 1: Recall correct expiration option for jwt.sign

    The option to set token lifetime is expiresIn with string or number format.
  2. Step 2: Validate option values

    Only jwt.sign({ email, role }, secretKey, { expiresIn: '30m' }) uses expiresIn: '30m' correctly; others use invalid keys or formats.
  3. Final Answer:

    jwt.sign({ email, role }, secretKey, { expiresIn: '30m' }) -> Option B
  4. Quick Check:

    Use expiresIn with '30m' for 30 minutes expiry [OK]
Hint: Use expiresIn: '30m' to set 30-minute token expiry [OK]
Common Mistakes:
  • Using expiresAt or expiration instead of expiresIn
  • Passing number without units as string
  • Misspelling expiresIn option
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard