[英]How to secure a static route with Express and Nodejs
I use Node (latest version) + Express, also latest Version. 我使用Node(最新版本)+ Express,也是最新版本。 I have 2 folders, public and secured. 我有2个公用和安全文件夹。 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();
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.