我有多个路线页面。让我们调用父路线(index.js)和子路线(child1.js,child2.js)。所有这些页面都指定了多个路径。其中一些需要保护,一些更好的不受保护。
在JSON web令牌和jsonwebtoken包的帮助下,我创建了一个中间件,用于检查用户是否可以访问特定路由。用户只有在传递了有效的json令牌后才能访问它们。这是针对受保护的路线。 对于不受保护的路线,不需要这样的东西。
我将中间件保存在单独的页面中,然后使用module.exports
将其导出到路由页面,然后将其注入受保护的路由。
但它没有用。我尝试使用POSTman客户端访问受保护的路由,但请求永远不会被发送。装载机微调器显示。
这是我的代码:
AUTH-middleware.js
module.exports = function () {
return function (req, res, next) {
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.secret, function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
}
else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
}
}
我的父路线:index.js
var router = require('express').Router();
var protected = require('./auth-middleware')();
var childRoute1 = require('./child1');
var childRoute2 = require('./child2');
router.use('/child1', childRoute1);
router.use('/child2', childRoute2);
//unprotected parent route
router.get('/', function (req, res, next) {
res.json('Unprotected route 1!');
});
//unprotected parent route
router.get('/albums/what',protected, function (req, res, next) {
res.json('album!');
});
router.route('/login').post(User.loginUser);
module.exports = router;
我的孩子路线1:child1.js
var child1Router = require('express').Router();
var protected = require('./auth-middleware')();
var ChildC = require('../controllers/childController');
child1Router.route('/all',protected).get(ChildC.fetchAllChildData); //protected
child1Router.route('/my').get(ChildC.fetchMyChildData); //unprotected
module.exports = child1Router;
child2与child1类似。所以我不包括它。
更新
我已经在app.js文件(主文件)中包含了身体解析器
const express = require('express');
var bodyParser = require('body-parser');
app = express();
var routes = require('./routes/index');
var port = process.env.PORT || 3000; //set our port
//configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', routes);
app.use(function (req, res) {
res.status(404).send({ url: req.originalUrl + ' not found' })
});
app.listen(port);
console.log('Magic happens on port ' + port);
module.exports = app;
答案 0 :(得分:1)
您可以使用verify
方法将中间件导出为对象,如下所示:
<强> AUTH-middleware.js 强>
module.exports = {
verify: function (req, res, next) {
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.secret, function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
}
else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
}
}
您现在可以要求var authMiddleware = require('../auth-middleware');
<强> index.js 强>
var router = require('express').Router();
var authMiddleware = require('./auth-middleware');
var childRoute1 = require('./child1');
var childRoute2 = require('./child2');
router.use('/child1', childRoute1);
router.use('/child2', childRoute2);
// unprotected parent route
router.get('/', function (req, res, next) {
res.json('Unprotected route 1!');
});
// protected parent route
router.get('/albums/what', authMiddleware.verify, function (req, res, next) {
res.json('album!');
});
router.route('/login').post(User.loginUser);
module.exports = router;
或者您可以将受保护的路线置于router.user
下,如下所示:
router.use('/child1', childRoute1);
router.use('/child2', childRoute2);
// unprotected parent route
router.get('/', function (req, res, next) {
res.json('Unprotected route 1!');
});
router.route('/login').post(User.loginUser);
// route middleware to verify token
router.use(authMiddleware.verify);
// protected parent route
router.get('/albums/what', function (req, res, next) {
res.json('album!');
});