Bird
Raised Fist0
NestJSframework~20 mins

Local strategy (username/password) in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Local Strategy Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when the local strategy validates a user with correct credentials?
Consider a NestJS local strategy that checks username and password. What is the output when a user provides the correct username and password?
NestJS
async validate(username: string, password: string) {
  const user = await this.authService.validateUser(username, password);
  if (!user) {
    throw new UnauthorizedException();
  }
  return user;
}
AReturns the user object to the caller for further processing
BThrows a ForbiddenException error
CReturns null without throwing an error
DLogs the user out immediately
Attempts:
2 left
💡 Hint
Think about what the validate method should do when credentials are correct.
📝 Syntax
intermediate
2:00remaining
Which option correctly implements the Passport local strategy constructor in NestJS?
Choose the correct constructor code snippet for a NestJS local strategy extending PassportStrategy(LocalStrategy).
NestJS
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';

export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({ usernameField: 'email' });
  }

  async validate(username: string, password: string) {
    // validation logic
  }
}
Aconstructor(private authService: AuthService) { super({ usernameField: 'email' }); }
Bconstructor(authService: AuthService) { super({ usernameField: 'email' }); this.authService = authService; }
Cconstructor() { super({ usernameField: 'email' }); }
Dconstructor(private authService: AuthService) { super(); this.authService = authService; }
Attempts:
2 left
💡 Hint
Remember how to pass options to the PassportStrategy constructor and inject services.
🔧 Debug
advanced
2:00remaining
Why does this local strategy fail to throw UnauthorizedException even with incorrect credentials?
Review the validate method below. Why does it fail to throw UnauthorizedException even when the username and password are incorrect? async validate(username: string, password: string) { const user = await this.authService.validateUser(username, password); if (user === null) { throw new UnauthorizedException(); } return user; }
NestJS
async validate(username: string, password: string) {
  const user = await this.authService.validateUser(username, password);
  if (user === null) {
    throw new UnauthorizedException();
  }
  return user;
}
AThe validate method is missing an await keyword
BauthService.validateUser returns undefined instead of null, so the condition fails
CUnauthorizedException is thrown before calling validateUser
DThe method returns user before checking if it is null
Attempts:
2 left
💡 Hint
Check what value validateUser returns when credentials are invalid.
❓ state_output
advanced
2:00remaining
What is the value of 'user' after validate returns successfully?
Given this local strategy validate method: async validate(username: string, password: string) { const user = await this.authService.validateUser(username, password); if (!user) { throw new UnauthorizedException(); } return user; } If validateUser returns { id: 5, username: 'alice' }, what is the value of user after validate returns?
NestJS
async validate(username: string, password: string) {
  const user = await this.authService.validateUser(username, password);
  if (!user) {
    throw new UnauthorizedException();
  }
  return user;
}
AThrows UnauthorizedException
Bundefined
Cnull
D{ id: 5, username: 'alice' }
Attempts:
2 left
💡 Hint
What does the method return if the user is valid?
🧠 Conceptual
expert
2:00remaining
Which option best explains why the local strategy uses 'usernameField' option?
In NestJS local strategy, why do we pass { usernameField: 'email' } to the PassportStrategy constructor?
ATo rename the validate method parameter from username to email automatically
BTo enforce that only email addresses can be used as usernames in the database
CTo tell Passport to use the 'email' field from the request instead of the default 'username' field
DTo enable Passport to hash the email field before validation
Attempts:
2 left
💡 Hint
Think about how Passport extracts credentials from the login form.

Practice

(1/5)
1. What is the main purpose of the LocalStrategy in NestJS authentication?
easy
A. To encrypt user passwords
B. To generate JWT tokens for users
C. To handle user registration
D. To verify username and password for user login

Solution

  1. Step 1: Understand the role of LocalStrategy

    The LocalStrategy is designed to check user credentials, specifically username and password, during login.
  2. Step 2: Differentiate from other strategies

    Unlike JWT or OAuth strategies, LocalStrategy focuses on validating credentials, not token generation or registration.
  3. Final Answer:

    To verify username and password for user login -> Option D
  4. Quick Check:

    LocalStrategy = username/password check [OK]
Hint: Local strategy always checks username and password [OK]
Common Mistakes:
  • Confusing LocalStrategy with JWT token generation
  • Thinking LocalStrategy handles user registration
  • Assuming LocalStrategy encrypts passwords
2. Which method must be implemented in a NestJS LocalStrategy class to check user credentials?
easy
A. authenticate()
B. validate()
C. login()
D. verify()

Solution

  1. Step 1: Recall LocalStrategy method names

    In NestJS, the LocalStrategy requires a validate method to check username and password.
  2. Step 2: Confirm method purpose

    The validate method returns the user if credentials are correct or throws an error if not.
  3. Final Answer:

    validate() -> Option B
  4. Quick Check:

    Credential check method = validate() [OK]
Hint: LocalStrategy uses validate() to check credentials [OK]
Common Mistakes:
  • Using authenticate() which is not a LocalStrategy method
  • Confusing login() with validate()
  • Assuming verify() is required
3. Given this LocalStrategy snippet, what happens if the password is incorrect?
async validate(username: string, password: string) {
  const user = await this.authService.validateUser(username, password);
  if (!user) {
    throw new UnauthorizedException();
  }
  return user;
}
medium
A. The function returns null silently
B. The user object is returned anyway
C. An UnauthorizedException is thrown stopping login
D. The password is reset automatically

Solution

  1. Step 1: Analyze the validate method logic

    If validateUser returns no user (password incorrect), the code throws UnauthorizedException.
  2. Step 2: Understand exception effect

    Throwing UnauthorizedException stops the login process and signals failure.
  3. Final Answer:

    An UnauthorizedException is thrown stopping login -> Option C
  4. Quick Check:

    Wrong password = UnauthorizedException thrown [OK]
Hint: Throw UnauthorizedException if user not found [OK]
Common Mistakes:
  • Assuming user is returned even if password is wrong
  • Thinking function returns null without error
  • Believing password resets automatically
4. Identify the error in this LocalStrategy validate method:
async validate(username: string, password: string) {
  const user = this.authService.validateUser(username, password);
  if (!user) {
    throw new UnauthorizedException();
  }
  return user;
}
medium
A. Missing await before authService.validateUser call
B. UnauthorizedException should not be thrown
C. validate method should not be async
D. username and password parameters are reversed

Solution

  1. Step 1: Check async call usage

    The method calls validateUser which returns a Promise, but lacks await.
  2. Step 2: Understand consequences of missing await

    Without await, user is a Promise, so if (!user) check is incorrect and login logic breaks.
  3. Final Answer:

    Missing await before authService.validateUser call -> Option A
  4. Quick Check:

    Async calls need await to get results [OK]
Hint: Always await async calls in validate() [OK]
Common Mistakes:
  • Forgetting await on async service calls
  • Throwing exceptions incorrectly
  • Misordering parameters
5. You want to customize the LocalStrategy to allow login with either username or email. Which change is best to implement in the validate method?
hard
A. Modify validateUser to accept a single identifier and check both username and email
B. Add a second validate method for email login
C. Use two separate LocalStrategy classes for username and email
D. Change the password parameter to accept email instead

Solution

  1. Step 1: Understand the goal

    Allow login by username or email using one validate method.
  2. Step 2: Best approach

    Modify validateUser to accept one identifier and check if it matches username or email, then verify password.
  3. Step 3: Why other options fail

    Adding multiple validate methods or strategies complicates logic; changing password parameter is incorrect.
  4. Final Answer:

    Modify validateUser to accept a single identifier and check both username and email -> Option A
  5. Quick Check:

    One validate method, flexible identifier [OK]
Hint: Use one validate method checking username or email [OK]
Common Mistakes:
  • Creating multiple validate methods unnecessarily
  • Using separate strategies for username and email
  • Confusing password parameter with identifier
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