Cannot get JWT token in middleware










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.










share|improve this question






















  • In the line jwt.verify you have a return, try removing it, and just keep the return false and return next()

    – Hosar
    Nov 13 '18 at 12:37















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.










share|improve this question






















  • In the line jwt.verify you have a return, try removing it, and just keep the return false and return next()

    – Hosar
    Nov 13 '18 at 12:37













4












4








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.










share|improve this question














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.







node.js express jwt middleware






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 13 '18 at 10:08









Svetoslav PetrovSvetoslav Petrov

435419




435419












  • In the line jwt.verify you have a return, try removing it, and just keep the return false and return next()

    – Hosar
    Nov 13 '18 at 12:37

















  • In the line jwt.verify you have a return, try removing it, and just keep the return false and return next()

    – Hosar
    Nov 13 '18 at 12:37
















In the line jwt.verify you have a return, try removing it, and just keep the return false and return next()

– Hosar
Nov 13 '18 at 12:37





In the line jwt.verify you have a return, try removing it, and just keep the return false and return next()

– Hosar
Nov 13 '18 at 12:37












2 Answers
2






active

oldest

votes


















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();

[...]





share|improve this answer























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

    – Volodia
    Nov 22 '18 at 10:40



















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.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53278551%2fcannot-get-jwt-token-in-middleware%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    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();

    [...]





    share|improve this answer























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

      – Volodia
      Nov 22 '18 at 10:40
















    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();

    [...]





    share|improve this answer























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

      – Volodia
      Nov 22 '18 at 10:40














    2












    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();

    [...]





    share|improve this answer













    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();

    [...]






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 15 '18 at 16:04









    Svetoslav PetrovSvetoslav Petrov

    435419




    435419












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

      – Volodia
      Nov 22 '18 at 10:40


















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

      – Volodia
      Nov 22 '18 at 10:40

















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

    – Volodia
    Nov 22 '18 at 10:40






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

    – Volodia
    Nov 22 '18 at 10:40














    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.






    share|improve this answer



























      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.






      share|improve this answer

























        0












        0








        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 13 '18 at 12:31









        Souvik DeySouvik Dey

        15235




        15235



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53278551%2fcannot-get-jwt-token-in-middleware%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            How to read a connectionString WITH PROVIDER in .NET Core?

            Node.js Script on GitHub Pages or Amazon S3

            Museum of Modern and Contemporary Art of Trento and Rovereto