Local Strategy (username/password) Authentication in NestJS
📖 Scenario: You are building a simple NestJS backend that allows users to log in using a username and password. This is a common way websites check who you are before letting you access private information.We will create a local authentication strategy that checks the username and password against a small list of users stored in the code.
🎯 Goal: Build a NestJS local strategy that verifies a username and password from a predefined list of users.When a user tries to log in, the system will check if the username and password match one of the users and allow access if correct.
📋 What You'll Learn
Create a list of users with usernames and passwords
Add a configuration variable for password minimum length
Implement the local strategy to validate username and password
Complete the strategy class with necessary decorators and methods
💡 Why This Matters
🌍 Real World
Local username/password authentication is a common way to secure web applications by verifying user identity before granting access.
💼 Career
Understanding how to implement authentication strategies in NestJS is essential for backend developers building secure APIs and services.
Progress0 / 4 steps
1
Create the users list
Create a constant array called users with these exact user objects: { username: 'john', password: 'changeme' } and { username: 'maria', password: 'guess' }.
NestJS
Hint
Use const users = [ ... ] and include the exact user objects inside the array.
2
Add password minimum length config
Create a constant called MIN_PASSWORD_LENGTH and set it to 6.
NestJS
Hint
Use const MIN_PASSWORD_LENGTH = 6; to set the minimum password length.
3
Implement validate method in LocalStrategy
Create a class called LocalStrategy with a method validate(username: string, password: string) that returns the user object if the username and password match a user in users. Return null if no match is found or if the password length is less than MIN_PASSWORD_LENGTH.
NestJS
Hint
Use users.find to locate the user and check password length before returning.
4
Complete LocalStrategy with decorator and export
Add the @Injectable() decorator above the LocalStrategy class and export the class with export class LocalStrategy.
NestJS
Hint
Import Injectable from @nestjs/common and add @Injectable() above the class. Use export class LocalStrategy.
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
Step 1: Understand the role of LocalStrategy
The LocalStrategy is designed to check user credentials, specifically username and password, during login.
Step 2: Differentiate from other strategies
Unlike JWT or OAuth strategies, LocalStrategy focuses on validating credentials, not token generation or registration.
Final Answer:
To verify username and password for user login -> Option D
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
Step 1: Recall LocalStrategy method names
In NestJS, the LocalStrategy requires a validate method to check username and password.
Step 2: Confirm method purpose
The validate method returns the user if credentials are correct or throws an error if not.
Final Answer:
validate() -> Option B
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
Step 1: Analyze the validate method logic
If validateUser returns no user (password incorrect), the code throws UnauthorizedException.
Step 2: Understand exception effect
Throwing UnauthorizedException stops the login process and signals failure.
Final Answer:
An UnauthorizedException is thrown stopping login -> Option C