简体   繁体   中英

How to secure a static route with Express and Nodejs

I use Node (latest version) + Express, also latest Version. I have 2 folders, public and secured. The secured folder should only be accessible after login.

I've create a login system by myself, now I wonder how I can secure the route to this "secure-folder".

I was thining about setting a static route to my "secured" folder (like I did with the public one) and then check whether the user is logged in, but it doesn't work.

This is what I thought should work...

(...)
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'secured')));
(...)

function requireLogin(req, res, next) {
  if (req.session.loggedIn) {
    next(); // allow the next route to run
  } else {
    // require the user to log in
    res.redirect("/login"); 
  }
}

app.all("/secured/*", requireLogin, function(req, res, next) {
  next(); 

});

Specify a different folder for your private statics on a separate route

app.use(express.static(path.join(__dirname, 'public')));
app.use('/private', express.static(path.join(__dirname, 'private')));

Then you can use your middleware on each request

app.all('/private/*', function(req, res, next) {
  if (req.session.loggedIn) {
    next(); // allow the next route to run
  } else {
    // require the user to log in
    res.redirect("/login"); 
  }
})

before your first app.use,

add something like

app.use(function(req, res, next) {
  if (req.url.match(/^\/secured\//)) {
    return requireLogin(req, res, next);
  }
  next();
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM