具有多种策略的 Nestjs 护照身份验证

标签 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;
  }
还有一些人大多喜欢这个。但是因为我在里面抛出了未经授权的异常,所以我不能在同一个路由/ Controller 上使用它们中的多个。例如。
  @UseGuards(AuthGuard(['employee', 'admin']))
第一个崩溃导致错误。如何解决这个问题?

最佳答案

@xxx_coder_noscope 您对策略的看法有点错误。这里的策略是一种如何从定义的位置(HTTP header 、查询、参数、cookie 等)获取特殊 token 、 key 等的方法。从 validate() 返回的实体方法将作为 user 注入(inject)到请求对象中属性(property)。
稍后通过创建 EmployeeGuardEmployeeGuard implements CanActivete并覆盖 canActivate()方法按类型检查用户角色并返回 bool 值以允许或拒绝访问端点

关于具有多种策略的 Nestjs 护照身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62670332/

相关文章:

node.js - 在 sequelize getter 和 setter 函数中使用时出现 "Argument of type is not assignable to parameter of type"错误

NestJS/中间件是否实例化为单例?

nestjs - 嵌套类验证器 minDate 即使日期更大也会抛出错误

node.js - Nestjs readFileSync 返回无法读取未定义的属性 'readFileSync'

nestjs - 如何在Nestjs中使用express的路由特定中间件?

nestjs - 在 Nest.js 中将实体映射到 DTO(反之亦然)

nestjs - DTO 在 PATCH 调用期间可选

javascript - NestJs 验证管道无法正常工作

typescript - 为什么在指定类型后我得到 "UnhandledPromiseRejectionWarning: Error: Undefined type error. Make sure are providing an explicit type"?

node.js - 如何使用@ResolveField 在 nestjs/graphql 中创建多级嵌套查询?