Search code examples
javascriptnode.jsexpress-jwt

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;

Solution

  • 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)
    }