Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS' Passport Local Strategy "validate" method never called

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);
  }
like image 459
Skull Cutter Avatar asked Dec 11 '25 02:12

Skull Cutter


1 Answers

EDIT

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.

like image 103
Jay McDoniel Avatar answered Dec 13 '25 23:12

Jay McDoniel