DEV Community

Margaret W.N
Margaret W.N

Posted on

Verify a JWT Token

My previous post involved generating a random number that would serve as a token secret. I was generating a new random number each time a user made post request to the login route, which was good for learning but impractical. We only need one token secret, this is because we'll be using the token secret to verify our tokens. So instead i logged out the random number, copied it and saved it to a config.js file.

module.exports = {
  'secret': 'ed5a2131834e4e0dd1fb7b9d1d0a1db71802a13a02011b19a98152b7988ad9215613c064a0ded303c39ab328b6181494'
}
Enter fullscreen mode Exit fullscreen mode

I'll be using this token secret to create and verify tokens. I'll include my the config.js file in my userController.js file, then replace the secret (previous post) in jwt.sign() with config.secret.

const config = require('../config/config');
Enter fullscreen mode Exit fullscreen mode
const token = jwt.sign({ id: user._id }, config.secret, {
        expiresIn: 86400 
      });
Enter fullscreen mode Exit fullscreen mode

Next i want to verify the token. I'll add this functionality to my getUsers function. I'll retrieve the token from the request headers and save it to a variable: token. If no token exists i'll send back a message: 'no token Provided'. If a token exists we pass it to jwt.verify() together with our token secret for verification. On successful verification it should return a list of all users, failure to which it will return an error message.
Disclaimer: I'm probably not following the best practices here but it's part of the learning process.

const getUsers = (req, res) => {
  let token = req.headers['x-access-token'];
  if(!token){
    return res.status(401).send({auth: false, message:'no token provided'});
  }
  jwt.verify(token, config.secret, function(err, users) {
    if (err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });

    User.find((err, users) => {
        if (err) {
          return res.sendStatus(404);
        }
        return res.json(users)
      });
  });
Enter fullscreen mode Exit fullscreen mode

I'll head over to postman and send a Get request to the /users route. Since no token was passed i'll get an error message back.
Alt Text

I'll send a Post request to the /users/login route, and copy the generated token.
Alt Text

I'll try and get the users again this time passing the token to the request.Alt Text
My users are retrieved successfully.

That's it for today.

Ps:
I'm still trying to wrap my head around Authentication. There might be a hell lot of updates on this posts.

Day 31

Oldest comments (0)