首页 > 解决方案 > 如何在nestJs中使用护照本地策略对多个实体进行身份验证?

问题描述

我有两个不同的实体:公司和用户都必须使用电子邮件和密码进行身份验证。我设置了 2 个不同的类来扩展护照策略,如下所示:

@Injectable()
export class LocalStrategyCompany extends PassportStrategy(Strategy) {
  constructor(private companyAuthenticationService: CompanyAuthenticationService) {
    super({
      usernameField: 'email'
    });
  }
  async validate(email: string, password: string): Promise<Company> {
    const company = this.companyAuthenticationService.getAuthenticatedCompany(email, password);
    if (!company) {
      throw new UnauthorizedException();
    }
    return company;
  }
  }

和本地身份验证警卫类:

@Injectable()
export class LocalAuthenticationGuard extends AuthGuard('local') {}

以及身份验证控制器中的此登录方法:

@HttpCode(200)
  @UseGuards(LocalAuthenticationGuard)
  @Post('log-in')
  async logIn(@Req() request: RequestWithUser) {
    const {user} = request;
    const cookie = this.authenticationService.getCookieWithJwtToken(user.id);
    request.res.setHeader('Set-Cookie', cookie);
    return user;
  }

我在 CompanyAuthentication 模块中创建了相同的内容,但是当我尝试使用公司登录时,我收到了错误的凭据错误。你能帮忙吗?顺便说一句,我正在关注本教程:https ://wanago.io/2020/05/25/api-nestjs-authenticating-users-bcrypt-passport-jwt-cookies/

标签: nestjsnestjs-passport

解决方案


我认为这会this.companyAuthenticationService.getAuthenticatedCompany返回一个 Promise,因此您需要使用await关键字。

  const company = await this.companyAuthenticationService.getAuthenticatedCompany(email, password);

推荐阅读