0
0
NestJSframework~30 mins

Local strategy (username/password) in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Import Injectable from @nestjs/common and add @Injectable() above the class. Use export class LocalStrategy.