Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to protect routes in express.js?

For example, in Meteor, there's something like

Router.plugin('ensureSignedIn');
Router.plugin('ensureSignedIn', {
  except: ['home', 'atSignIn', 'atSignUp', 'atForgotPassword']
});

So unsigned user cannot access other routes except above four.

How to do this in express.js? I'm using passport.js also.

like image 280
Sato Avatar asked Feb 24 '16 23:02

Sato


People also ask

How do you protect routes in react?

To protect routes, the private components must also have access to the isLoggedIn value. You can do this by creating a new component that accepts the isLoggedIn state as a prop and the private component as a child. For instance, if your new component is named "Protected", you would render a private component like this.

Are Express sessions secure?

If you run with https and your physical computer is secure from outsiders, then your express session cookie is protected from outsiders when stored locally and is protected (by https) when in transport to the server.


1 Answers

I'm not familiar with Meteor, but you can do something like the following, assuming you want to make pages available to only authenticated users (passport).

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated())
    return next();
  else
    // Return error content: res.jsonp(...) or redirect: res.redirect('/login')
}

app.get('/account', ensureAuthenticated, function(req, res) {
  // Do something with user via req.user
});

The ensureAuthenticated function is just an example, you can define your own function. Calling next() continues the request chain.

like image 198
Ash Avatar answered Nov 14 '22 22:11

Ash