Thursday, 15 November 2018

Cannot get JWT token in middleware

I am trying to use JWT tokens in a project I am working on at the moment. I am trying to use a middleware to verify the JWT token before passing it to the next handler. However, I have a weird issue that I do not get the JWT token in the middleware, but if I pass it to the next handler I get the token. Hopefully the example below will explain it:

I have implemented a PING method and some logging to show you what happens. My setup looks like so:

this._express.use((req, res, next) => {
    console.log('AUTH');
    return jwt.verify(req.headers['x-access-token'], 'mysecret', (err, decoded) => {
        if (err) {
            console.log(`ERROR: ${err}`);
            return false;
        }

        console.log('DECODED');
        return next();
    });
});

//Health Check
this._express.get('/ping', (req, res) => {
    console.log(`PING`);
    return res.status(200).send('pong');
});

If I execute this piece of code the output is:

node_1        | AUTH
node_1        | ERROR: JsonWebTokenError: jwt must be provided

However, if I use the next() callback in the middleware:

this._express.use((req, res, next) => {
    console.log('AUTH');
    next(); // This is the only thing that is different
    return jwt.verify(req.headers['x-access-token'], 'mysecret', (err, decoded) => {
        if (err) {
            console.log(`ERROR: ${err}`);
            return false;
        }

        console.log('DECODED');
        return next();
    });
});

//Health Check
this._express.get('/ping', (req, res) => {
    console.log(`PING`);
    return res.status(200).send('pong');
});

The output is the following:

node_1        | AUTH
node_1        | ERROR: JsonWebTokenError: jwt must be provided
node_1        | AUTH
node_1        | PING
node_1        | DECODED

I don't have much experience with JWT tokens, and please excuse me if it is something obvious.



from Cannot get JWT token in middleware

No comments:

Post a Comment