Search code examples
javascriptnode.jsexpressrole-base-authorization

Need a better way for "role based authentication middleware" on express.js


What I have done:

router.get('/apps', authController.authenticateUser, appController.getApps);

router.get('/roles', authController.authenticateAdmin, roleController.getRoles);

What I want do:

router.get('/apps', authController.authenticate('USER'), appController.getApps);

router.get('/roles', authController.authenticate('ADMIN'), roleController.getRoles);

When I'm passing parameters like this way getting this error ==> Error: Route.post() requires a callback function but got a [object Undefined]

Thank You.


Solution

  • All express middlewares should return a function that accepts three parameters (request, response, next). In your case, your middleware is registered as an object. Instead, return an anonymous function(closure) from the authenticate() method and resister it as express middleware.

    AuthController:

    module.exports.authenticate = function (role) {
       return function(req, res, next) {
          //add your authentication logic here based on the role
       }
    }
    

    Router

    router.get('/apps', authController.authenticate('USER'), appController.getApps);