nestjspassport.jshttp-status-code-401guardauth-guard

NestJS Local Auth Guard always returning 401 Unauthorized


I'm having a problem, which from what I've searched is kinda normal to happen. I'm trying to use the local auth guard and the local strategy from NestJS, still without the JWT part, and I'm always getting the 401 Unauthorized. My code is very similar with the documentation code from the NestJS docs, here's my local.strategy.ts:

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super();
  }

  async validate(email: string, password: string): Promise<any> {
    const user = await this.authService.validateUser(email, password);

    if (!user) {
      throw new UnauthorizedException();
    }

    return user;
  }

Here's the validateUser from my auth.service.ts:

async validateUser(email: string, password: string): Promise<any> {
    const user = await this.usersService.findOneWithEmail(email);

    const isPasswordValid = await bcrypt.compare(password, user.password);

    if (user && isPasswordValid) {
      const { ...result } = user;
      return result;
    }

    return null;
  }

Now my findOneWithEmail function from users.service.ts:

async findOneWithEmail(email: string) {
    return await this.userModel.findOne({
      email: email,
    });
  }

Note that, ultimately I want to use a DTO instead of the email and password in the validate functions, but I've tried with the DTO and it was not working, then switched it up to email and password, as it is in the docs. Also note that I have all my imports, exports and providers as it is in docs, so I think that might not be the problem.

If you need and more relevant info, please let me know.

Thanks in advance.

I expect it to return the Passport user, I think, instead I'm just getting the 401 constantly.


Solution

  • I found the problem and solved it. It was an easy solution. I found it here: Nestjs returns 401 (Unauthorized) even with valid user ft. passport-local

    Looks like if you want to send your own param in the validate you have to include it in super(), passport expects a username and a password.