Bird
Raised Fist0
NestJSframework~10 mins

Why authentication secures NestJS APIs - Test Your Understanding

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the module that helps with authentication in NestJS.

NestJS
import { [1] } from '@nestjs/passport';
Drag options to blanks, or click blank then click option'
ASecurityModule
BAuthModule
CJwtModule
DPassportModule
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing JwtModule instead of PassportModule
Using a non-existent module like SecurityModule
2fill in blank
medium

Complete the code to protect a route using the AuthGuard in NestJS.

NestJS
@UseGuards([1]('jwt'))
@Get('profile')
getProfile() {
  return 'User profile data';
}
Drag options to blanks, or click blank then click option'
AAuthGuard
BJwtGuard
CRolesGuard
DSecurityGuard
Attempts:
3 left
💡 Hint
Common Mistakes
Using RolesGuard which is for authorization, not authentication
Using JwtGuard which is not a built-in guard
3fill in blank
hard

Fix the error in the JWT strategy validate method to correctly return the user object.

NestJS
async validate(payload: any) {
  const user = await this.userService.findById(payload.sub);
  if (!user) {
    throw new UnauthorizedException();
  }
  return [1];
}
Drag options to blanks, or click blank then click option'
Apayload.sub
Buser
Cpayload
Duser.id
Attempts:
3 left
💡 Hint
Common Mistakes
Returning payload instead of user
Returning only user.id which loses user details
4fill in blank
hard

Fill both blanks to create a JWT token with a secret and expiration time.

NestJS
const token = this.jwtService.sign(payload, { secret: [1], expiresIn: [2] });
Drag options to blanks, or click blank then click option'
A'mySecretKey'
B'1h'
C'30m'
D'secret123'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a number instead of string for secret
Setting expiresIn to an invalid format
5fill in blank
hard

Fill all three blanks to create a NestJS guard that extracts the JWT token from the request header.

NestJS
canActivate(context: ExecutionContext) {
  const request = context.switchToHttp().getRequest();
  const authHeader = request.headers['[1]'];
  if (!authHeader) return false;
  const token = authHeader.split('[2]')[1];
  return this.jwtService.verify(token, { secret: '[3]' });
}
Drag options to blanks, or click blank then click option'
Aauthorization
BBearer
CmySecretKey
Dtoken
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'token' as header key
Splitting by wrong string
Using wrong secret string

Practice

(1/5)
1. Why is authentication important for securing NestJS APIs?
easy
A. It stops strangers from accessing protected routes.
B. It speeds up the API response time.
C. It automatically fixes bugs in the code.
D. It changes the API's data format.

Solution

  1. Step 1: Understand the purpose of authentication

    Authentication verifies who is using the API to prevent unauthorized access.
  2. Step 2: Identify the effect on API security

    By stopping strangers, authentication protects sensitive data and functionality.
  3. Final Answer:

    It stops strangers from accessing protected routes. -> Option A
  4. Quick Check:

    Authentication = Stops strangers [OK]
Hint: Authentication blocks unknown users from API access [OK]
Common Mistakes:
  • Thinking authentication speeds up API
  • Believing it fixes code bugs
  • Confusing authentication with data formatting
2. Which of the following is the correct way to apply an authentication guard in a NestJS controller?
easy
A. @AuthGuard('jwt') export class MyController {}
B. @UseGuards(AuthGuard('jwt')) export class MyController {}
C. @UseAuthGuard('jwt') export class MyController {}
D. @GuardUse(Auth('jwt')) export class MyController {}

Solution

  1. Step 1: Recall NestJS guard syntax

    Guards are applied using the @UseGuards() decorator with the guard class or strategy inside.
  2. Step 2: Match the correct syntax for JWT guard

    The correct syntax is @UseGuards(AuthGuard('jwt')) to apply the JWT strategy.
  3. Final Answer:

    @UseGuards(AuthGuard('jwt')) export class MyController {} -> Option B
  4. Quick Check:

    @UseGuards(AuthGuard('jwt')) = Correct syntax [OK]
Hint: Use @UseGuards with AuthGuard('jwt') for authentication [OK]
Common Mistakes:
  • Using wrong decorator names like @AuthGuard
  • Swapping order of decorator and parameters
  • Misspelling @UseGuards
3. Given this NestJS controller snippet, what happens when a request without a valid JWT token is sent?
@UseGuards(AuthGuard('jwt'))
@Get('profile')
getProfile() {
  return { message: 'Access granted' };
}
medium
A. The request is denied with a 401 Unauthorized error.
B. The request returns an empty response.
C. The request causes a server crash.
D. The request is allowed and returns { message: 'Access granted' }.

Solution

  1. Step 1: Understand AuthGuard('jwt') behavior

    This guard checks for a valid JWT token and blocks requests without it.
  2. Step 2: Predict response for missing or invalid token

    Without a valid token, the guard denies access and returns a 401 Unauthorized error.
  3. Final Answer:

    The request is denied with a 401 Unauthorized error. -> Option A
  4. Quick Check:

    Invalid token = 401 error [OK]
Hint: No valid JWT means 401 Unauthorized response [OK]
Common Mistakes:
  • Assuming request passes without token
  • Expecting server crash on missing token
  • Thinking empty response is returned
4. Identify the error in this NestJS authentication guard usage:
@UseGuards(AuthGuard)
@Get('data')
getData() {
  return { data: 'secret' };
}
medium
A. The @UseGuards decorator is misspelled.
B. The getData method should be async.
C. AuthGuard is missing the strategy name like 'jwt'.
D. The route path 'data' is invalid.

Solution

  1. Step 1: Check AuthGuard usage

    AuthGuard requires a strategy name like 'jwt' to know which authentication method to use.
  2. Step 2: Identify missing strategy parameter

    Here, AuthGuard is used without ('jwt'), causing it to not work properly.
  3. Final Answer:

    AuthGuard is missing the strategy name like 'jwt'. -> Option C
  4. Quick Check:

    AuthGuard needs strategy name [OK]
Hint: Always provide strategy name to AuthGuard like 'jwt' [OK]
Common Mistakes:
  • Forgetting to add strategy name to AuthGuard
  • Thinking method must be async
  • Assuming route path 'data' is invalid
5. You want to secure a NestJS API route so only logged-in users can access it. Which combination correctly applies authentication and explains why it secures the API? Options: A) Use @UseGuards(AuthGuard('jwt')) to check user identity before route access, preventing strangers. B) Use @UseInterceptors(AuthInterceptor) to log requests, which blocks unauthorized users. C) Use @UseFilters(AuthFilter) to catch errors, which stops unauthorized access. D) Use @UsePipes(AuthPipe) to validate data, which ensures only valid users access the route.
hard
A. Use @UsePipes(AuthPipe) to validate data, which ensures only valid users access the route.
B. Use @UseInterceptors(AuthInterceptor) to log requests, which blocks unauthorized users.
C. Use @UseFilters(AuthFilter) to catch errors, which stops unauthorized access.
D. Use @UseGuards(AuthGuard('jwt')) to check user identity before route access, preventing strangers.

Solution

  1. Step 1: Identify the correct NestJS feature for authentication

    Guards are designed to control access by checking user identity before route execution.
  2. Step 2: Understand why guards secure APIs

    Using @UseGuards(AuthGuard('jwt')) ensures only authenticated users with valid JWT tokens can access the route, blocking strangers.
  3. Final Answer:

    Use @UseGuards(AuthGuard('jwt')) to check user identity before route access, preventing strangers. -> Option D
  4. Quick Check:

    Guards + AuthGuard('jwt') = Secure API access [OK]
Hint: Use guards with AuthGuard('jwt') to secure routes [OK]
Common Mistakes:
  • Confusing interceptors, filters, or pipes with authentication guards
  • Thinking logging or error handling blocks unauthorized users
  • Assuming data validation equals authentication
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