NestJS NestJS Authentication & Security 1 — Questions and Answers
Question 1: Which NestJS package integrates Passport.js strategies for authentication?
- @nestjs/jwt
- @nestjs/passport (Correct answer)
- @nestjs/security
- @nestjs/auth
Correct answer: @nestjs/passport
@nestjs/passport wraps Passport.js strategies into NestJS guards and provides AuthGuard() for route protection.
Question 2: What does `AuthGuard('jwt')` do in NestJS?
- Generates a JWT token for the current user
- Validates the JWT token from the request and populates req.user (Correct answer)
- Refreshes an expired JWT automatically
- Signs outgoing responses with a JWT signature
Correct answer: Validates the JWT token from the request and populates req.user
AuthGuard('jwt') invokes the Passport JWT strategy to extract, verify, and decode the token, attaching the payload to req.user.
Question 3: Which decorator applies a guard to an entire controller in NestJS?
- @UseGuards() on the controller class (Correct answer)
- @ApplyGuard() on the controller class
- @Guard() on each method
- @Protect() on the module
Correct answer: @UseGuards() on the controller class
@UseGuards() placed on a controller class applies the specified guard(s) to every route handler within that controller.
Question 4: How do you make a single route publicly accessible when JWT auth is applied globally in NestJS?
- Set `optional: true` in AuthGuard options
- Use a custom @Public() decorator combined with a reflector check in the guard (Correct answer)
- Add the route to the `exclude` array in app.module
- Use @SkipAuth() built-in decorator
Correct answer: Use a custom @Public() decorator combined with a reflector check in the guard
A custom @Public() metadata decorator combined with Reflector in the guard's canActivate() allows bypassing JWT validation for specific routes.
Question 5: What is the purpose of the `validate()` method in a Passport strategy class?
- It validates the shape of the request body
- It receives the decoded token payload and returns the user object to attach to the request (Correct answer)
- It validates environment variables on startup
- It runs input sanitization on query parameters
Correct answer: It receives the decoded token payload and returns the user object to attach to the request
validate() is called after the token is verified; its return value is attached to req.user and made available to route handlers.
Question 6: Which NestJS package provides JWT signing and verification utilities?
- @nestjs/security
- @nestjs/crypto
- @nestjs/jwt (Correct answer)
- @nestjs/passport
Correct answer: @nestjs/jwt
@nestjs/jwt wraps the jsonwebtoken library, providing JwtService with sign() and verify() methods for token management.
Which NestJS package integrates Passport.js strategies for authentication?