4

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.

1
  • In the line jwt.verify you have a return, try removing it, and just keep the return false and return next() Commented Nov 13, 2018 at 12:37

2 Answers 2

2

So I managed to find what the issue was. The problem lies with CORS. In particular, the middleware works as expected however due to CORS a preflight request is sent which does not have the JWT token which is why I got the error in the first example. I have updated the middleware to skip the preflight requests:

 if (req.headers['access-control-request-headers'] === 'x-access-token') { return next(); } [...] 
Sign up to request clarification or add additional context in comments.

1 Comment

Are you sure that this is a place to make a change in code? ;) For example, when you provide malformed input in some way...
0

I'm guessing this to be a problem of req.headers['x-access-token']. Once next() is called, the control goes to the next endpoint route. You should provide JWT as initials to the token.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.