如何在 nestJs 中使用护照本地策略对多个实体进行身份验证?

时间:2021-05-31 14:44:05

标签: nestjs nestjs-passport

我有两个不同的实体:公司和用户都必须使用电子邮件和密码进行身份验证。 我设置了 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') {}

和 auth 控制器中的这个登录方法:

@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/

1 个答案:

答案 0 :(得分:0)

我认为 fig = plt.figure(constrained_layout=True) gs = fig.add_gridspec(18, 9) ax = fig.add_subplot(gs[3:6, 1:3], zorder=1) #this is the target subplot ax = draw_football_field(ax, other_args) # modify axes instance from 'this' fig 会返回一个 Promise,因此您需要使用 this.companyAuthenticationService.getAuthenticatedCompany 关键字。

await