【发布时间】: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