Retrieve request body/header variables in JWT strategy using Nest JS

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

The JWT structure within the JwtStrategy currently appears as follows:

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

The JwtAuthGuard is structured 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;
  }
}

An error occurs when returning anything other than the request object from the guards:

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

Is there a method to access the request body or header variables within the strategy?

Answer №1

For more information on this topic, check out the solution detailed at this Stack Overflow post. To be able to retrieve the request within the validate method, I found that it was necessary to include the parameter passReqToCallback and assign a value of true when invoking super in the constructor.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

utilizing Typescript object within an array of objects

How can I optimize typing this nested array of objects? const myItem: Items[] = [{ id: 1, text: 'hello', items: [{ id: 1, text: 'world' }] }] One way to approach this is by using interfaces: interface It ...

What is the best way to utilize ajax and javascript for creating a dynamic image gallery on a website

I am looking to create an image portfolio that launches when a user presses a thumbnail. The code for building the portfolio only executes upon pressing the thumbnail. Here is my current setup. Essentially, I want to incorporate something like this into m ...

JavaScript Variables Lose Their Values

Similar Inquiry: How can I get the response from an AJAX call in a function? I have written a function that fetches numerical data from an online file. Although the file retrieval is successful (verified by the alert message), I encounter an issue whe ...

The middleware function in my express server is not being identified

Currently, I am tackling server-side rendering in React and have developed a basic server in Express. However, I'm encountering the "TypeError('app.use() requires a middleware function')" error repeatedly. Below is a snippet of my app.js: v ...

Creating an HTML Table with Database Data utilizing JSP, Java, and JavaScript

Challenge: I am currently tasked with developing a web application for a university course using JSP, Java, Javascript, and JQuery without relying on any external frameworks or libraries. The main goal is to create a calendar-like table that displays cours ...

The order of execution is not maintained for $.getJSON() calls within the $.each() loop

As I iterate through an HTML table, I am making a $.getJSON() request based on the data in each row. My goal is to retrieve the data from that $.getJSON call and update the corresponding row with it. Unfortunately, when I run my code, it seems to be execu ...

What is the technical process behind conducting A/B testing at Optimizely?

I'm currently experimenting with Google Analytics and Content Experiments for A/B testing on my website, but I'm encountering some challenges in making it seamless. To utilize the Google API properly, a few steps need to be taken. Firstly, I nee ...

Have you ever encountered the frustration of being unable to navigate to the next page even after successfully logging in due to issues

I'm currently utilizing Vue and Firebase to build my application. One of the features I want to implement is the redirect method using vue-router. Within my vue-router code, I've included meta: { requiresAuth: true } in multiple pages as middlew ...

Struggling with inserting a fresh form into every additional <div> section

During my quest to develop a To-Do list application, I encountered a new challenge. In my current implementation, every time a user clicks on New Category, a new div is supposed to appear with a custom name and a specific number of forms. However, an issu ...

Best practices for configuring a gulpfile.ts

I have configured a gulpfile.ts for my project based on this example from GitHub found here. (I won't be sharing my exact gulpfile.ts as it is similar, just slightly more complex) Every time I run a gulp task, I encounter these 4 errors: [11:53:23] ...

Issue with Parcel / React 18 App.js failing to refresh cache

Currently, I am developing a React application for my school project. However, I have encountered an issue where certain components are not rendering in my App.js file. Strangely, when I place these components as child components of App.js, they do render ...

What is the best way to eliminate a CSS style from a div?

I have implemented jQuery Autosize to automatically adjust the height of textarea elements. It works perfectly when I focus on the textarea element. However, when I blur out of the textarea, I want to reset the height to its default value. I am unsure of ...

What is the correct way to utilize browser actions for sending keys with the "?" symbol in Protractor?

I'm facing an issue in my tests with a particular line of code browser.actions().sendKeys(Key.chord(Key.CONTROL, '?')).perform(); Interestingly, it works fine with another symbol. For example: browser.actions().sendKeys(Key.chord(Key.CONT ...

When I try to make an on-demand revalidation API call on Vercel, it takes so long that it ends up timing

Inspired by Kent C. Dodds, I have created a blog using Github as my Content Management System (CMS). All of my blog content is stored in the same repository as the code, in mdx format. To streamline the process, I set up a workflow that detects changes i ...

Validating Cognito credentials on the server-side using Node.js

I am currently developing server-side login code for AWS Cognito. My main goal is to verify the existence of a user logging into the identity pool and retrieve the attributes associated with them. With email login, everything is running smoothly using the ...

JavaScript code to modify a table row

I have a dynamic table that increases with Firebase data, and I am trying to incorporate a delete and edit button on each row. While the remove button is working fine, I am facing issues with implementing the edit functionality. Although I came across some ...

Retrieve the property value from a nested object using a key that contains spaces

Presenting my object: let obj = { innerObj: { "Key with spaces": "Value you seek" } } Upon receiving, I am unaware of the content within obj. I possess a string variable holding the key to access the value. It appears as follows: let ke ...

Trouble with Mongoose save() function failing to update data

I am currently working on enhancing a fully functioning CRUD app by adding a new feature that allows users to update a list of vendors. They have the ability to add new vendors, update existing ones, and delete vendors. While the add and delete functions a ...

Revise the validation process for the drop-down menu and input field

Looking for help with text field validation based on a dropdown selection. There are two scenarios to consider: 1. User changes dropdown value and then enters text in the field. 2. User enters text in field and then changes dropdown. I've written cod ...

Alter the background color of a React application with a single click in a spontaneous manner

When I attempted to change the background color of the entire page randomly by clicking a button, it only changed the background of the div element. Here is the code snippet I used: import React from "react"; class Home extends React.Component { ...