0
0
NestJSframework~10 mins

Why authentication secures NestJS APIs - Test Your Understanding

Choose your learning style9 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