Search code examples
javascriptnode.jsjwttoken

Implement jwt-permissions on NodeJS - UnauthorizedError


I am new to the use of Nodejs but I confess that I am loving, I am using tokens Jwt for authentication of users, simple thing, they log and win a token. but I want to put permissions on the routes, I've been reading about express-jwt-permissions, but using it in my application I'm getting the following error at POSTMAN: UnauthorizedError: user object "user" was not found. Check your configuration.

customerRoutes.js

const router = require('express').Router();

var jwt = require('jsonwebtoken');
var guard = require('express-jwt-permissions')()
const customerController = require('../controllers/customerController');




  function verifyToken(req, res, next) {
  // Get auth header value
  const bearerHeader = req.headers['authorization'];
  // Check if bearer is undefined
  if(typeof bearerHeader !== 'undefined') {
  // Split at the space
   const bearer = bearerHeader.split(' ');
   // Get token from array
   const bearerToken = bearer[1];
     // Set the token
    req.token = bearerToken;
    // Next middleware
   next();
   } else {
   // Forbidden
   res.sendStatus(403);
  }

  }

   router.post('/posts',verifyToken,guard.check('admin'),
   customerController.posts);

   module.exports = router;

this is how my token looks : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwZXJtaXNzaW9ucyI6WyJhZG1pbiJdLCJpYXQiOjE1Mzc0MDg0NzMsImV4cCI6MTUzNzQ0ODQ3M30.8l1vezWWz3Gmb5M3N0DgsmCl-nZHK2c3GP-dKzYDLRU


Solution

  • From the documentation of express-jwt-permissions

    This middleware assumes you already have a JWT authentication middleware such as express-jwt.

    And then tracing towards express-jwt documentation, with the first example:

    var jwt = require('express-jwt');
    
    app.get('/protected',
      jwt({secret: 'shhhhhhared-secret'}),
      function(req, res) {
        if (!req.user.admin) return res.sendStatus(401);
        res.sendStatus(200);
      });
    

    And associate with your encountered error, it's safe to say that express-jwt-permissions middleware is expecting a populated req.user field with the value of an object (then I actually checked their source code https://github.com/MichielDeMey/express-jwt-permissions/blob/master/index.js#L11 and proves that it is the case).

    So my suggestion would be either use express-jwt which does the work for you and is known to work with express-jwt-permissions, or populate a req.user object within your verifyToken middleware by yourself (requires decoding of the JWT), something like:

    // decode JWT
    // get decoded token.permissions
    req.user = {
      permissions: token.permissions
    };
    

    Before invoking next() to the next middleware.

    Note that you can also tweak express-jwt-permissions to expect a different field than user (but still need to live in the req namespace of express middleware life-cycle), as well as a different name than permissions field inside the token payload. See https://www.npmjs.com/package/express-jwt-permissions#configuration for details. But either way, the bottom line is you'll need to decode the token first.