【问题标题】:Access request body/header variables within jwt strategy - nest js在 jwt 策略中访问请求正文/标头变量 - 嵌套 js
【发布时间】:2022-01-25 22:42:15
【问题描述】:

如何在策略中访问标头变量/正文?

目前,JWT 如下所示:

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly appConfigService: AppConfigService,
    private readonly usersService: UsersService
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: appConfigService.configs.JWT_SECRET_KEY
    });
  }

  async validate(payload: { id: string }) {
    const user = await this.usersService.findBusinessUserById(
      'BUSINESS_ID', // TODO: replace this with business id from the request
      payload.id
    );

    if (user) {
      return user;
    }

    return null;
  }
}

而守卫看起来像这样:

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(private readonly reflector: Reflector) {
    super();
  }

  canActivate(
    context: ExecutionContext
  ): boolean | Promise<boolean> | Observable<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass()
    ]);

    return isPublic ? true : super.canActivate(context);
  }

  getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    const req = ctx.getContext().req;

    return req;
  }
}

如果我尝试返回除警卫请求之外的任何内容,我会得到以下信息

TypeError: Cannot read properties of undefined (reading 'authorization')
    at JwtStrategy._jwtFromRequest

有没有办法从策略中的头部获取请求体或变量?

【问题讨论】:

    标签: javascript typescript graphql nestjs


    【解决方案1】:

    在这里找到答案https://stackoverflow.com/a/68180268/6226852。为了在 validate 方法中访问请求,我需要在构造函数中调用 super 时传递 passReqToCallback 并将其值设置为 true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 2015-08-10
      • 1970-01-01
      • 2021-03-05
      • 1970-01-01
      • 2019-12-26
      相关资源
      最近更新 更多