我有一个运行express
和jsonwebtoken
的Node应用程序。在每次请求api调用jsonwebtoken之前,我都进行了检查。我已手动排除下面的路线。有没有更好的方法从这里排除一些路线?我怎么能这样做?
import * as express from 'express';
import * as jwt from 'jsonwebtoken';
import UserCtrl from './controllers/user';
export default function setRoutes(app) {
const router = express.Router();
// route middleware to verify a token
router.use(function (req, res, next) {
if ((req.method == 'POST' || req.method == 'OPTIONS') && (req.url == '/user' || req.url == '/login' || req.url == '/user/activate')) {
next();
} else {
// check header or url parameters or post parameters for token
var token = req.headers.authorization;
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, process.env.SECRET_TOKEN, function (err, decoded) {
if (err) {
return res.status(401).send({
success: false,
message: 'Sign in to continue.'
});
} else {
// if everything is good, save to request for use in other routes
next();
}
});
} else {
// if there is no token
// return an error
return res.status(401).send({
success: false,
message: 'Sign in to continue.'
});
}
}
});
const userCtrl = new UserCtrl();
router.route('/login').post(userCtrl.login);
router.route('/user/activate').post(userCtrl.activate);
router.route('/users').get(userCtrl.getAll);
router.route('/users/count').get(userCtrl.count);
router.route('/user').post(userCtrl.signup);
router.route('/user/:id').get(userCtrl.get);
router.route('/user/:id').put(userCtrl.update);
router.route('/user/:id').delete(userCtrl.delete);
app.use('/api/v1', router);
}
答案 0 :(得分:8)
您可以提取功能(验证令牌的功能)并将其用作路由器中特定路由的中间件。这样您就不必指定需要在函数内登录的路由。
像这样:
function isLoggedIn(req, res, next) {
// check header or url parameters or post parameters for token
var token = req.headers.authorization;
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, process.env.SECRET_TOKEN, function(err, decoded) {
if (err) {
return res.status(401).send({
success: false,
message: 'Sign in to continue.'
});
} else {
// if everything is good, save to request for use in other routes
next();
}
});
} else {
// if there is no token
// return an error
return res.status(401).send({
success: false,
message: 'Sign in to continue.'
});
}
}
const userCtrl = new UserCtrl();
// Routes that require no login
router.post('/login', userCtrl.login);
router.get('/users', userCtrl.getAll);
router.post('/user/activate', userCtrl.activate);
// Routes that require login
router.get('/users/count', isLoggedIn, userCtrl.count);
router.post('/user', isLoggedIn, userCtrl.signup);
router.get('/user/:id', isLoggedIn, userCtrl.get);
router.put('/user/:id', isLoggedIn, userCtrl.update);
router.delete('/user/:id', isLoggedIn, userCtrl.delete);
app.use('/api/v1', router);
您可以阅读有关Express Middlewares here的更多信息。