Is placing this code inside of a route enough to protect pages from unauthenticated users?
if (!req.user) return res.send(401, "Not allowed in");
Passport is a popular, modular authentication middleware for Node. js applications. With it, authentication can be easily integrated into any Node- and Express-based app. The Passport library provides more than 500 authentication mechanisms, including OAuth, JWT, and simple username and password based authentication.
Passport is authentication middleware for Node. js. As it's extremely flexible and modular, Passport can be unobtrusively dropped into any Express-based web application. A comprehensive set of strategies supports authentication using a username and password, Facebook, Twitter, and more.
You can use the request itself to transfer some additional parameters from and to the strategy function. In the following example the two parameters _toParam and _fromParam are used for this concern. app. get('/auth/facebook/:appId', function(req,res,next){ req.
Passport. js out of the box is safe as your implementation of it to protect routes from unauthorized access. For example if you forget to apply the middleware to certain routes they would not be protected, if you make a mistake in configuring the authentication strategy you may open up your application to an attack.
You can use req.isAuthenticated()
to check if the request is authenticated or not.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
app.get('/server', ensureAuthenticated, routes.server.get);
app.get('/login', routes.login.get);
Or like this
app.all('*', function(req,res,next){
if (req.path === '/' || req.path === '/login')
next();
else
ensureAuthenticated(req,res,next);
});
It's enough as long as you aren't leaking a route somewhere. Just make sure your routes are in the proper order.
//checks to be sure users are authenticated
app.all("*", function(req, res, next){
if (!req.user)
res.send(403);
else
next();
});
//additional routes will require authentication due to the order of middleware
app.get("/admin", ....
However, if you moved the admin route above the global one, the admin route would no longer be protected. You might want to purposefully put your login page earlier so it doesn't require authentication for example.
A correction for user568109's answer, with express 4 the code must be like this :
app.all('*', function(req,res,next) {
if (req.path === '/' || req.path === '/login')
next();
else
ensureAuthenticated(req,res,next);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With