访问jwt策略nest-js中的请求体/头变量



如何访问策略中的头变量/主体?

目前,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

有没有一种方法可以从策略的头中获取请求主体或变量?

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

最新更新