NestJS Local Auth Guard 总是返回 401 Unauthorized

问题描述 投票:0回答:1

我遇到了一个问题,根据我的搜索,这是很正常的情况。我正在尝试使用本地身份验证防护和 NestJS 的本地策略,但仍然没有 JWT 部分,并且我总是收到 401 Unauthorized。我的代码与 NestJS 文档中的文档代码非常相似,这是我的 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;
  }

这是我的 auth.service.ts 中的 validateUser:

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;
  }

现在我的 findOneWithEmail 函数来自 users.service.ts:

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

请注意,最终我想在验证功能中使用 DTO 而不是电子邮件和密码,但我尝试过使用 DTO 但它不起作用,然后将其切换为电子邮件和密码,就像在文档。另请注意,我拥有文档中的所有导入、导出和提供程序,因此我认为这可能不是问题。

如果您需要更多相关信息,请告诉我。

提前致谢。

我认为它会返回 Passport 用户,但我只是不断收到 401。

nestjs passport.js http-status-code-401 guard auth-guard
1个回答
0
投票

我需要更多信息来帮助您。 您应该首先检查用户在下面的代码中返回的是预期值还是 null。

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

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

return user;

之后 如果用户始终为空,则在获取用户的过程中存在问题。 你应该继续调试实际上没有按你预期工作的地方。 例如:validateUser、findOneWithEmail 或其他...

我认为获取用户的过程一定存在问题。 让我们继续跟踪这个错误。给我更多更新的信息谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.