dmx dmx -4 years ago 81
Node.js Question

Node js : How can I integrate authorization and authentication to my node application?

In my node application, I have an

that can make all requests and the normal user that has the right to make only certain requests.


admin cans make:

post on
/root, /user, /tools

simple users can make:

post on
/users, /tools

If a simple user tries to make a request on
, he just receives and error message.

How can I handle this is node js? which package, if possible few examples.


Answer Source

A general approach should be define a custom middleware to verify the authentication

function VerifyUser(req, res, next){
   return next(); //call the next middleware
 next(err); //call the error middleware 


error handler

app.use(function(err, req, res, next) {
    if(!err) return next(); 
    res.status(500).json(new Error('error happened'));

and then for each route that needs authentication bind the VerifyUser middleware before the router middleware. Since in express the middleware order is relevant, VerifyUser will be called at first, and if the branch reach the next() call your routing function will be triggered.

Authenticated routes:

router.get('/root', VerifyUser, function(req, res){
 //if you reach this point means the user has been granted the access


Non-authenticated routes:

router.get('/tools', function(req, res){

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download