A JWT strategy in NestJS is used to authenticate users by verifying JSON Web Tokens sent with requests. It helps secure routes by checking if the token is valid and extracting user information from it.
Click to reveal answer
beginner
Which NestJS package provides the tools to implement a JWT strategy?
The @nestjs/passport package along with passport-jwt is used to implement JWT strategies in NestJS. @nestjs/passport integrates Passport.js with NestJS, and passport-jwt handles JWT validation.
Click to reveal answer
intermediate
In a JWT strategy, what is the role of the validate() method?
The validate() method checks the decoded JWT payload and returns user data if valid. This data is then attached to the request object, allowing access to user info in protected routes.
Click to reveal answer
intermediate
How does the JWT strategy extract the token from incoming requests?
The JWT strategy uses an extractor function, commonly JwtFromRequest.ExtractJwt.fromAuthHeaderAsBearerToken(), which looks for the token in the Authorization header as a Bearer token.
Click to reveal answer
beginner
Why is it important to keep the JWT secret key safe in a NestJS application?
The JWT secret key signs and verifies tokens. If exposed, attackers can create fake tokens and access protected resources. Keeping it safe ensures token integrity and application security.
Click to reveal answer
What does the JWT strategy primarily verify in a request?
AThe validity of the JSON Web Token
BThe user's password
CThe request's IP address
DThe request's HTTP method
✗ Incorrect
The JWT strategy checks if the JSON Web Token sent with the request is valid and not tampered with.
Which header usually contains the JWT in a request?
AUser-Agent
BContent-Type
CAccept
DAuthorization
✗ Incorrect
The JWT is typically sent in the Authorization header as a Bearer token.
In NestJS, which method inside the JWT strategy returns user info after token validation?
Asign()
Bauthenticate()
Cvalidate()
Ddecode()
✗ Incorrect
The validate() method processes the decoded token payload and returns user information.
Which package is NOT required to implement JWT strategy in NestJS?
A@nestjs/passport
Bexpress-session
Cpassport-jwt
Djsonwebtoken
✗ Incorrect
express-session is not needed for JWT strategy, which is stateless and does not use sessions.
What happens if the JWT secret key is leaked?
AAttackers can forge tokens and access protected routes
BTokens expire immediately
CUsers get logged out automatically
DThe application crashes
✗ Incorrect
If the secret key is leaked, attackers can create fake tokens and bypass authentication.
Explain how a JWT strategy works in NestJS to protect routes.
Think about how the token is checked and how user info becomes available in your app.
You got /4 concepts.
Describe the steps to set up a JWT strategy in a NestJS application.
Focus on packages, class setup, and how validation is done.
You got /5 concepts.
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
Step 1: Understand JWT strategy role
The JWT strategy is used to check the user's identity by verifying the token sent with requests.
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.
Final Answer:
To verify user identity by checking the JWT token in requests -> Option C
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
Step 1: Identify correct package for JwtStrategy
In NestJS, JwtStrategy is usually imported from 'passport-jwt' which provides the Passport JWT strategy.
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.
Final Answer:
import { JwtStrategy } from 'passport-jwt'; -> Option A
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' }?
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
Step 1: Review constructor usage
The constructor correctly calls super() with options including jwtFromRequest and secretOrKey.
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.
Final Answer:
process.env.JWT_SECRET might be undefined causing runtime error -> Option B
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
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.
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.
Final Answer:
Override validate() to check payload.role and throw UnauthorizedException if not 'admin' -> Option D
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 unknownstrongwhile earning +1 Grip toward your certificate.