如何在Express.js中设置身份验证中间件 [英] How to setup an authentication middleware in Express.js
问题描述
我已经建立了一个Web应用程序,其中包含一些需要登录的内部页面.我将Node与Express.js一起使用来设置服务器并控制路由和身份验证正常进行.
I have set up a web application with some internal pages requiring a login. I used Node with Express.js to set up the server and controlling the routes and authentication works fine.
我在与以下问题相关的问题上提出了@zanko建议:相同的应用程序,以避免像现在这样在每个页面的路由中复制身份验证代码.
I came up to a @zanko suggestion in a question related to the same application to avoid the replication of the authentication code in the route of every page, like is now.
此刻我的app.js看起来像这样(以下是摘录):
At the moment my app.js looks like this (the following is an excerpt):
var session = require('express-session');
//use sessions for tracking logins
app.use(session({
secret: 'mercuia',
resave: true,
saveUninitialized: false,
store: new MongoStore({
mongooseConnection: db
})
}));
// serve static files from template
app.use(express.static(__dirname + '/public'));
// include routes
var routes = require('./routes/router');
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('File Not Found');
err.status = 404;
next(err);
});
// error handler
// define as the last app.use callback
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.send(err.message);
});
和我的身份验证方法(在routes.js中)如下所示(在示例中,对于路由/clientPage):
and my authentication method (in routes.js) looks like this (in the example, for the route /clientPage):
// GET route after registering
router.get('/clientPage', function (req, res, next) {
User.findById(req.session.userId)
.exec(function (error, user) {
if (error) {
return next(error);
} else {
if (user === null) {
var err = new Error('Not authorized! Go back!');
err.status = 400;
return next(err);
} else {
return res.sendFile(path.join(__dirname + '/../views/clientPage.html'));
}
}
});
});
我该如何编写身份验证中间件(使用相同的逻辑)并针对所有且仅用于必需的路由调用它?
How can I write an authentication middleware instead (using the same logic) and call it for all and only the requiring routes?
推荐答案
您可以创建一个名为auth.js
的新模块,然后使用它来检查用户是否被授权:
You can create a new module called auth.js
and then use it to check if users are authorized or not:
auth.js
module.exports.isAuthorized = function(req, res, next) {
User.findById(req.session.userId).exec(function (error, user) {
if (error) {
return next(error);
} else {
if (user === null) {
var err = new Error('Not authorized! Go back!');
err.status = 400;
return next(err);
} else {
return next();
}
}
});
}
routes.js
var auth = require('./auth');
// GET route after registering
router.get('/clientPage', auth.isAuthorized, function (req, res, next) {
res.sendFile(path.join(__dirname + '/../views/clientPage.html'));
});
这篇关于如何在Express.js中设置身份验证中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!