Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Check each node.js request for authentication credentials

Check each node.js request for authentication credentials

Problem

I'm using node.js with Express and connect-auth to authenticate users.

This is the verification when requesting /index:

if(req.isAuthenticated()) {
  res.redirect('/dashboard');
} else {
  res.render('index', { layout: 'nonav' });
}

However, after logging out and going back to f.e. '/dashboard', I can see the dashboard.

How can I put the Authentication check to every request to make sure there's a valid user at all times?

Update I don't have any problems with the authentication, everything works fine! I need a solution which checks every route/request if there's a valid user, without putting a function or if-statement in the route-implementation, as the whole App needs a valid user anyway. The Express-Authentication-Example uses "restrict" in the route-definition, which is close, but with many Routes it can easily be forgotten.

Problem courtesy of: Patrick

Solution

app.all('*',function(req,res,next){
    if(req.isAuthenticated()){
        next();
    }else{
        next(new Error(401)); // 401 Not Authorized
    }
});
// NOTE: depending on your version of express,
// you may need to use app.error here, rather
// than app.use.
app.use(function(err,req,res,next){
    // Just basic, should be filled out to next()
    // or respond on all possible code paths
    if(err instanceof Error){
        if(err.message === '401'){
            res.render('error401');
        }
    }
});

If you define the all route before routes which require authentication and after routes which do not (such as the home page, login, etc) then it should only affect the routes that need it. Alternatively you could use a RegExp instead of '*', which would include a subpath or list of paths that require authentication.

Another option would be to create a function to include in each route that requires auth:

function IsAuthenticated(req,res,next){
    if(req.isAuthenticated()){
        next();
    }else{
        next(new Error(401));
    }
}
app.get('/login',function(req,res,next){
    res.render('login');
});
app.get('/dashboard',IsAuthenticated,function(req,res,next){
    res.render('dashboard');
});
app.get('/settings',IsAuthenticated,function(req,res,next){
    res.render('settings');
});
Solution courtesy of: Zikes

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Check each node.js request for authentication credentials

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×