我是 Express 4 的新手,我想知道如何实现这一点:我使用jwt来验证我的API的使用者,这样做我有一个非常简单的中间件来检查jwt令牌的有效性:
var requireValidToken = function(req, res, next) {
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
try {
var decoded = jwt.verify(token, req.app.get('superSecret'));
} catch(err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
}
req.user = decoded.user;
next();
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
};
这很好用,但现在,我想扩展这个以便能够检查用户的角色:
router.get('/anAdminRoute', requireRole('ROLE_ADMIN'), function (req, res, next) {
// some code...
});
所以我为此添加了一个中间件:
var requireRole = function(role) {
return function(req, res, next){
// Dummy tests...
if(req.user.role == roles.admin || req.user.role == role){
next();
} else {
return res.status(403)({
success: false,
message: "Token valid, but you don't have the right permission to access this resource :)"
});
}
}
}
但是当这个requireRole()函数显然检查有效的jwt令牌时,我想知道如何在这个函数中调用我的requireValidToken中间件,因此不必为我想要的每个路由显式调用它保护。
一个简单的解决方案是不使用 requireValidToken 作为中间件,但我仍然希望能够使用它来保护某些路由
编辑:解决方案
链接中间件很简单:
var middleware2 = function(param) {
return function(req, res, next){
middleware1(req, res, function(){
// middleware2 code
});
}
}
如果有兴趣的话,我的最终工作解决方案是验证用户角色:
var jwt = require('jsonwebtoken'),
roles = require('../models/user').roles;
// authentication middleware
// check if the given jwt token is valid
var requireValidToken = function(req, res, next) {
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
try {
var decoded = jwt.verify(token, req.app.get('superSecret'));
} catch(err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
}
req.user = decoded.user;
next();
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
};
var requireRole = function(role) {
return function(req, res, next){
requireValidToken(req, res, function(){
if(req.user.role == roles.admin || req.user.role == role){
next();
} else {
return res.status(403).send({
success: false,
message: "Token valid, but you don't have the right permission to access this resource :)"
});
}
});
}
}
module.exports = {
requireValidToken: requireValidToken,
requireRole: requireRole
}
答案 0 :(得分:9)
完全误读了你的问题。如果要在某些情况下调用requireValidToken
,可以将req和res对象传递给中间件函数以及匿名回调。如何获得中间件功能在很大程度上取决于您的应用程序架构,所以我假设我的上下文中有requireValidToken
:
var requireRole = function(role) {
return function(req, res, next){
// Dummy tests...
requireValidToken(req, res, function () {
if(req.user.role == roles.admin || req.user.role == role){
next();
} else {
return res.status(403)({
success: false,
message: "Token valid, but you don't have the right permission to access this resource :)"
});
}
});
}
};