javascript 如何使用 Express 和 Nodejs 保护静态路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14612774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:05:33  来源:igfitidea点击:

How to secure a static route with Express and Nodejs

javascriptnode.jsexpress

提问by Christian

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.

我使用 Node(最新版本)+ Express,也是最新版本。我有 2 个文件夹,公共文件夹和安全文件夹。只有在登录后才能访问受保护的文件夹。

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(); 

});

回答by zemirco

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"); 
  }
})

回答by Pascal Belloncle

before your first app.use,

在你的第一个 app.use 之前,

add something like

添加类似的东西

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