I'm trying to implement a Passport Local Strategy but the validate method is not working. When I do @UseGuards(AuthGuard("local")), it automatically throws an Unauthorized Exception without going through the validate method that I wrote. I have no idea what I'm doing wrong as the documentation did the same.
Here's my LocalStrategy class:
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(
@InjectRepository(UserRepository) private userRepository: UserRepository,
) {
super();
}
async validate(credentials: string, password: string): Promise<User> {
// this method is never called, I've already did some console.logs
const user = await this.userRepository.findByCredentials(credentials);
if (!user) throw new UnauthorizedException('Invalid credentials');
if (!(await argon2.verify(user.hash, password)))
throw new UnauthorizedException('Invalid credentials');
return user;
}
}
My AuthModule imports:
@Module({
imports: [TypeOrmModule.forFeature([UserRepository]), PassportModule],
controllers: [AuthController],
providers: [AuthService, LocalStrategy],
})
export class AuthModule {}
Example usage:
@Post("/login")
@UseGuards(LocalAuthGuard)
async login(@Body() loginDto: LoginDto) {
return this.authService.login(loginDto);
}
After spending more time with the code and doing a deep dive myself, it's not the fact that the validate method must have parameters named username and password, they could be bob and alice for all that matters, but what is important is that your req.body has two properties username and password. If you do not have req.body.username and req.body.password, then you will never make it to the validate of the LocalStrategy class.
The validate method must have the parameters username and password or the parameters must match the usernameField and passwordField values passed to super() in the constructor. If they do not match, the validate method will not be called. I think this comes from the fact that Nest calls validate(...args), but am not 100% certain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With