多种策略的Nestjs护照认证

时间:2020-07-01 05:34:28

标签: nestjs

我有多种身份验证策略,例如其中一种:

@Injectable()
export class EmployeeStrategy extends PassportStrategy(Strategy, 'employee') {
  constructor(
    private authService: AuthService,
    @Inject(appConfig.KEY)
    configService: ConfigType<typeof appConfig>,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: configService.EMPLOYEE_KEY,
    });
  }

  async validate({ phone }: JwtPayload) {
    const employee = await this.authService.authByRole(phone, Role.Employee);

    if (!employee) {
      throw new UnauthorizedException('insufficient scope');
    }

    return employee;
  }

还有其他一些人喜欢这个。但是由于我在其中抛出了未经授权的异常,因此我无法在同一路径/控制器上使用多个异常。例如

  @UseGuards(AuthGuard(['employee', 'admin']))

第一个崩溃导致错误。如何解决该问题?

1 个答案:

答案 0 :(得分:2)

@xxx_coder_noscope 你对策略的看法有点错误。这里的策略是一种如何从定义的位置(HTTP 标头、查询、参数、cookie 等)获取特殊令牌、密钥等的方法。 validate() 方法返回的实体将作为 user 属性注入请求对象。

稍后通过创建 EmployeeGuard 作为 EmployeeGuard implements CanActivete 并覆盖 canActivate() 方法按类型检查用户角色并返回布尔值以允许或拒绝访问端点