【问题标题】:How to authenticate multiple entities using passport local strategies in nestJs?如何在nestJs中使用护照本地策略对多个实体进行身份验证?
【发布时间】:2021-08-18 21:17:47
【问题描述】:

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

【问题讨论】:

    标签: nestjs nestjs-passport


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回复,但这并不能解决我的问题。
    猜你喜欢
    • 2020-04-20
    • 2017-03-21
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2022-07-19
    • 1970-01-01
    • 2015-09-10
    • 2018-11-24
    相关资源
    最近更新 更多