Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

276
Views
Access request body/header variables within jwt strategy - nest js

How can I access headers variables/body in a strategy?

Currently, the JWT looks like this:

@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;
  }
}

and the guard looks like this:

@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;
  }
}

If I try to return anything but the request from the guards I get the following

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

Is there a way to get the request body or variables from the header in the strategy?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Answer found here https://stackoverflow.com/a/68180268/6226852. In order to access the request in the validate method, I needed to pass passReqToCallback and set its value to true when calling super inside the constructor.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!