【问题标题】:Nestjs passport authentication with multiple strategies具有多种策略的 Nestjs 护照身份验证
【发布时间】:2020-10-21 12:25:01
【问题描述】:

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

@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']))

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

【问题讨论】:

  • 对不起,我不明白你的问题。你到底想做什么?
  • 为什么在同一条路线上需要多个?只需创建不同的登录路径,例如 /login/employee 和 /login/admin
  • 可以分享AuthGuard吗?

标签: nestjs


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-09-10
    • 2020-04-20
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2016-12-26
    • 2022-07-19
    • 2021-08-18
    • 2018-01-28
    相关资源
    最近更新 更多