简体   繁体   中英

JWT not working with express router

I am trying to implement an authentication system for the express REST API.

I got this code for using jsonwebtoken from a tutorial.

My auth middleware verifyToken is not working. Please help.

var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var models = require('../models');

function verifyToken(req, res, next) {
    var bearerHeader = req.headers['authorization'];
    if (typeof bearerHeader !== undefined) {

    } else {
        res.sendStatus(403)
    }
}

router.post('/tryjwt', verifyToken, (req, res, next) => {
    res.send('It worked');
});

router.get('/login', function (req, res, next) {
    const user = {
        id: 1,
        usename: 'ayoob',
        email: 'ayoob@gmail.com'
    }
    jwt.sign({ user: user }, 'secretkey', (err, token) => {
        res.json({ token: token })
    });
});

module.exports = router;

you did not perform any action when if (typeof bearerHeader !== undefined) is true.

Make sure next is called so that the current middleware can pass control to the next middleware

put this code snippet inside the if statement

try{
const decode = jwt.verify(bearerHeader, 'secretkey')
  //do something with the decode object 
   next()
}catch(err){
  res.sendStatus(403)
}

I think that the problem is the async nature of the jwt.sign() function - it continues to sign the token while it continues with your code - returning an empty json. You need to wait for the jwt.sign() to finish before the res.json({token}), or do something while the magic of the jwt is happening.

Hope I helped :)

ps It's better practice to use promises, so your code will be cleaner and you won't got into callback hell, and for better error handling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM