Bird
Raised Fist0
NestJSframework~20 mins

JWT strategy in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
JWT Strategy Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2: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 };
}
AThrows UnauthorizedException
B{ userId: 42, username: 'alice' }
C{ id: 42, name: 'alice' }
DReturns null
Attempts:
2 left
💡 Hint
The validate method transforms the JWT payload into a user object.
📝 Syntax
intermediate
2: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?
A
import { JwtStrategy } from '@nestjs/passport';
export class JwtStrategy extends JwtStrategy {}
B
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-jwt';
export class JwtStrategy extends PassportStrategy(Strategy) {}
C
import { Strategy } from 'passport-jwt';
export class JwtStrategy extends Strategy {}
D
import { PassportJwtStrategy } from 'passport';
export class JwtStrategy extends PassportJwtStrategy {}
Attempts:
2 left
💡 Hint
NestJS wraps Passport strategies with PassportStrategy class.
🔧 Debug
advanced
2: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; } }
AThe constructor is missing a call to super() with options.
BThe secret key is incorrect, causing token verification to fail.
CThe jwtFromRequest function is not extracting the token properly.
DThe validate method returns null, which Passport treats as failed validation.
Attempts:
2 left
💡 Hint
The validate method must return a user object or throw an exception.
🧠 Conceptual
advanced
2:00remaining
What is the purpose of the secretOrKey option in JWT strategy?
In NestJS JWT strategy configuration, what does the secretOrKey option do?
AIt specifies the secret used to verify the JWT signature.
BIt defines the expiration time of the JWT token.
CIt sets the algorithm used to sign the JWT token.
DIt extracts the JWT token from the request headers.
Attempts:
2 left
💡 Hint
Think about how JWT tokens are verified.
❓ state_output
expert
2: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?
AThe object returned by the JWT strategy's validate method.
BAn empty object {}.
CThe raw JWT token string from the Authorization header.
DThe decoded JWT payload without any transformation.
Attempts:
2 left
💡 Hint
The validate method controls what user data is attached to the request.

Practice

(1/5)
1. What is the main purpose of the JWT strategy in a NestJS application?
easy
A. To encrypt user passwords before saving to the database
B. To manage database connections securely
C. To verify user identity by checking the JWT token in requests
D. To serve static files like images and CSS

Solution

  1. Step 1: Understand JWT strategy role

    The JWT strategy is used to check the user's identity by verifying the token sent with requests.
  2. Step 2: Compare options with JWT purpose

    Only To verify user identity by checking the JWT token in requests matches this purpose; others relate to different concerns like encryption or static files.
  3. Final Answer:

    To verify user identity by checking the JWT token in requests -> Option C
  4. Quick Check:

    JWT strategy = verify token [OK]
Hint: JWT strategy always verifies tokens to identify users [OK]
Common Mistakes:
  • Confusing JWT strategy with password encryption
  • Thinking JWT handles static file serving
  • Mixing JWT with database connection management
2. Which of the following is the correct way to import the Passport JWT strategy in a NestJS file?
easy
A. import { JwtStrategy } from 'passport-jwt';
B. import { JwtStrategy } from '@nestjs/jwt';
C. import { JwtStrategy } from '@nestjs/passport';
D. import { JwtStrategy } from 'jsonwebtoken';

Solution

  1. Step 1: Identify correct package for JwtStrategy

    In NestJS, JwtStrategy is usually imported from 'passport-jwt' which provides the Passport JWT strategy.
  2. Step 2: Check other imports

    '@nestjs/jwt' provides JWT utilities like JwtService but not JwtStrategy itself; '@nestjs/passport' provides Passport integration but not JwtStrategy; 'jsonwebtoken' is for token creation/verification, not strategy.
  3. Final Answer:

    import { JwtStrategy } from 'passport-jwt'; -> Option A
  4. Quick Check:

    JwtStrategy import = 'passport-jwt' [OK]
Hint: JwtStrategy comes from 'passport-jwt' package in NestJS [OK]
Common Mistakes:
  • Importing JwtStrategy from '@nestjs/jwt'
  • Confusing JwtStrategy with jsonwebtoken functions
  • Using '@nestjs/passport' for JwtStrategy import
3. Given this JwtStrategy validate method, what will be returned if the token payload is { userId: 5, username: 'alice' }?
async validate(payload: any) {
  return { id: payload.userId, name: payload.username };
}
medium
A. { id: 5, name: 'alice' }
B. { userId: 5, username: 'alice' }
C. undefined
D. Throws an error because of missing return type

Solution

  1. Step 1: Analyze the validate method

    The method takes the payload and returns a new object with keys 'id' and 'name' mapped from 'userId' and 'username'.
  2. Step 2: Apply payload values

    Payload has userId=5 and username='alice', so returned object is { id: 5, name: 'alice' }.
  3. Final Answer:

    { id: 5, name: 'alice' } -> Option A
  4. Quick Check:

    Validate returns mapped user info [OK]
Hint: Validate returns a new object with selected payload fields [OK]
Common Mistakes:
  • Returning the original payload instead of mapped object
  • Assuming undefined return without explicit return
  • Thinking missing return type causes runtime error
4. Identify the error in this JwtStrategy constructor code snippet:
constructor(private readonly jwtService: JwtService) {
  super({
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: process.env.JWT_SECRET,
  });
}
medium
A. Missing call to super() with options object
B. process.env.JWT_SECRET might be undefined causing runtime error
C. jwtFromRequest should be a function, not a method call
D. JwtService should not be injected in JwtStrategy constructor

Solution

  1. Step 1: Review constructor usage

    The constructor correctly calls super() with options including jwtFromRequest and secretOrKey.
  2. Step 2: Check environment variable usage

    If process.env.JWT_SECRET is undefined, the strategy will fail at runtime because the secret key is missing.
  3. Final Answer:

    process.env.JWT_SECRET might be undefined causing runtime error -> Option B
  4. Quick Check:

    Missing JWT secret causes runtime failure [OK]
Hint: Always ensure JWT_SECRET env variable is set before running [OK]
Common Mistakes:
  • Assuming jwtFromRequest is incorrectly used
  • Thinking JwtService injection is invalid here
  • Ignoring possibility of missing environment variables
5. You want to create a custom JwtStrategy that extracts the user role from the token and denies access if the role is not 'admin'. Which approach correctly implements this logic?
hard
A. Modify jwtFromRequest to only accept tokens with 'admin' role
B. Set secretOrKey to 'admin' in constructor options to restrict roles
C. Use a guard to check user role after JwtStrategy validation without modifying validate()
D. Override validate() to check payload.role and throw UnauthorizedException if not 'admin'

Solution

  1. Step 1: Understand role check in JwtStrategy

    The validate() method is the right place to inspect the token payload and enforce role-based access by throwing exceptions if conditions fail.
  2. Step 2: Evaluate other options

    Setting secretOrKey to 'admin' is incorrect because it expects a secret key, not a role; guards can check roles but the question asks for JwtStrategy implementation; jwtFromRequest only extracts tokens, it cannot filter by role.
  3. Final Answer:

    Override validate() to check payload.role and throw UnauthorizedException if not 'admin' -> Option D
  4. Quick Check:

    Role check belongs in validate() method [OK]
Hint: Check roles inside validate() and throw exception if unauthorized [OK]
Common Mistakes:
  • Confusing secretOrKey with role filtering
  • Trying to filter roles in jwtFromRequest extractor
  • Ignoring validate() as place for access control
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