Retrieve the user without triggering a 401 error using the Express Passport + JWT middleware

I have integrated passport for authenticating calls to my express API. The setup is fairly standard:

/* Passport Configuration */

const jwtOptions = {
    jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer'),
    secretOrKey: config.auth.passport.key,
}

passport.use(
    'jwt',
    new JWT.Strategy(jwtOptions, (payload, done) => {
        console.log('Using JWT Strategy')
        User.findOne({ email: payload.email }, (err, user) => {
            if (err) {
                return done(err, false)
            }
            if (user) {
                done(null, user)
            } else {
                done(null, false)
            }
        })
    }),
)

/* Middleware */

const checkToken = passport.authenticate('jwt', { session: false })

const logAuthInfo = (req, res, next) => {
    console.log(req.headers)
    console.log(req.user)

}

/* Routes */

app.use(passport.initialize())

app.use('/graphql', checkToken, logAuthInfo, graphqlHTTP(graphQLConfig))
// Other REST routes, including login

After a successful login, I receive a JWT which works when used in requests to /graphql. However, an unauthenticated request without the token results in a 401 error. What I want to achieve is applying the checkToken middleware to all requests, and assigning req.user with either the authenticated user data or false, leaving authorization handling for later.

Upon making a token-less request, I noticed that the 'Using JWT Strategy' log does not appear in the console, indicating that the middleware isn't even executed.

Any suggestions on how to tackle this issue?

Answer №1

After posting this, I quickly discovered the solution. If you're facing the same issue, it's best not to rely on passport-jwt, but rather utilize the underlying jsonwebtoken.

My updated middleware now appears as follows:

const jwt = require('jsonwebtoken')
const PassportJwt = require('passport-jwt')

const getUserFromToken = (req, res, next) => {
    const token = PassportJwt.ExtractJwt.fromAuthHeaderWithScheme('Bearer')(req)
    jwt.verify(token, jwtSecret, (err, decoded) => {
        if (err) {
            req.user = false
            next()
            return
        }
        req.user = decoded
        next()
    })
}

app.use(getUserFromToken)
app.use('/graphql', graphqlHTTP(graphQLConfig))


// In my GraphQL resolvers

const userQuery = (obj, args, request, info) => {
        console.log(request.user) // Outputs 'false' or the serialized user data

        if (req.user) {
            // Perform actions authorized for this user...
        } else {
           // User is not logged in, perform limited operations..
       } 
}

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

Is there a straightforward method to determine if any of multiple conditionals are true and return that one?

I've searched high and low for answers to my query, but haven't found any that satisfy my needs. Perhaps I'm not using the right search terms... I'm dealing with a set of checkboxes that can be either "on" or "off". When these checkbo ...

Having trouble aligning the canvas of threejs next to a div

I am currently working on a shoe customizer project and facing difficulties in aligning my canvas (using three.js) next to the shoe customizer div. Although I posted the same question earlier, I did not receive a satisfying solution. I made some adjustment ...

Preventing Angular $rootElement.on('click') from affecting ReactJS anchor tag interactions

Running both AngularJS and ReactJS on the same page has caused an issue for me. Whenever I click on a ReactJS <a> tag, Angular's $rootElement.on('click) event is triggered and the page redirects. I need to perform some functionality in Re ...

Issue: the size of the requested entity is too large

Encountering an error message while using express: Error: request entity too large at module.exports (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/node_modules/raw-body/index.js:16:15) at json (/Users/ ...

Having difficulty generating a custom title due to an error

I'm experiencing an issue with creating a dynamic title for my website using HTML and JavaScript. The error message 'TypeError: null is not an object (evaluating 'document.getElementById("send").addEventListener')' keeps popping up ...

Executing a jQuery AJAX function when the timeout occurs

My goal is to dynamically reload my jQuery DataTables without having to refresh the entire page in order to fetch new data. Here's the initial function I have set up to kick off the process: $(document).ready(function() { $.ajax({ url:&apo ...

Tips for successfully passing a key to a React functional component within a .map() iteration?

I recently encountered a common issue with React that requires a 'key' prop for each child element when using the .map() method. In an attempt to address this, I created a key within a functional component like so... export default function Func ...

I'm having trouble getting my ms-auto to properly align the contents within a div

I've been trying to use the ms-auto class in my code, but it doesn't seem to be working properly: <div class="p-5 rounded bg-light text-dark"> <div class="container row"> <div class="col-sm-6"> ...

Transmit information from SerialPort to socket.io

I'm having difficulty with integrating socket.io, express, and node.js. I am successfully sending data from an Arduino to my command prompt using the serialport library. Now, I want to display this data on my web browser by utilizing the express libr ...

In Visual Studio, make sure to include a reference to AngularJS.min.js within another JavaScript file

In my AngularJS app, I am utilizing Visual Studio with separate folders. The AngularJS-min.js file is located in a different folder. My query is how can I correctly reference the AngularJS-min.js file in my app's JavaScript file to enable auto-suggest ...

Leveraging the sofa API within a minimalist Express server configuration

Hey there. I've set up a very basic express graphql server. I'm looking to utilize sofa-api to add REST functionality. I'm facing two issues: When accessing /api/hello, it should display "Hello World!", but currently it shows as null. ...

Create a React component using the value stored within an object

I am interested in creating an object: import React from "react"; import { Registration } from "../../"; const RouteObj = { Registration: { route: "/registration", comp: <Registration /> } }; export default RouteObj; Next, in a separat ...

Converting timeofday to numeric values in Google Line Chart

Working on a line chart presents a challenge as the format of the line remains unchangeable: function drawChart(){ var data = new google.visualization.DataTable(); data.addColumn('timeofday','quarter'); The desire ...

The synergy between Object.prototype and the bind() method

Currently, I am delving into ngInfiniteScroll while being a novice in JavaScript. Upon reviewing the demo of ngInfiniteScroll, I find it quite challenging to comprehend why Reddit.nextPage has been altered to Reddit.prototype.nextPage, and how the bind() m ...

Steps for adding a row as the penultimate row in a table

There aren't many solutions out there that don't rely on jQuery, but I'm looking to avoid it. The row content needs to be generated dynamically. Here is my flawed approach: function addRow() { let newRow = '<tr><td>B ...

What is the best way to structure JSON data when submitting a form with multiple fields using AJAX?

I am facing an issue with passing data to Ajax which requires the data to be bundled together. How can I gather the un-submitted text from my form fields and package it into a JSON object for sending to Ajax? <div id="editUserPinForm" class="ui rais ...

Automatically adjust zoom on focused object within a D3 force layout

I have implemented an autocomplete feature in my force directed graph to highlight selected nodes by coloring them red. Now, I am looking to implement a "zoom" functionality where the window magnifies to 400% the size of the selected node and centers it wi ...

Ways to transfer a value to another component in React

Currently, I am working on a project where users can add, edit, or delete movies from a list. While the addition and deletion functionalities are working fine, I am facing challenges with the editing feature. In my Movie component, I have included a text i ...

Tips for restricting the size of uploaded files or the quantity of files in multer express and effectively managing any errors

I am currently working on a code that requires me to set limits on file size or the number of files that can be uploaded. For instance, I want to restrict users from uploading more than 100 files at once or limit the total upload size to 100 mb. However, ...

The presence of additional backslashes in Node.js strings does not result in the backslashes displaying

In the code snippet below, the string looks like this: spawn('geth', ['attach', "ipc:\\.\pipe\geth"+"1"+".ipc"],... When displayed in the command output, it appears as: 'ipc:\\.pipegeth1.ipc' ...