我正在尝试在node.js
中构建授权系统,并且使用以下代码可以正常工作。
Authorize.js
const expressJwt = require('express-jwt');
const userService = require('../routes/users/user.service');
module.exports = authorize;
function authorize(roles = []) {
return expressJwt(
{
<<SOME SECRET>>,
isRevoked: (req, payload, done) => _isRevoked(req, payload, done, roles)
})
.unless(
{
path: [
]
});
}
async function _isRevoked(req, payload, done, roles) {
var user = await userService.getById(payload.sub);
var userRoles = payload.role;
// revoke token if user no longer exists
if (!user) {
console.log("Authorization: User not found")
return done(null, true);
}
//check if user is authorized
if (roles.length && !roles.every(elem => userRoles.indexOf(elem) > -1)) {
// user's role is not authorized
return done(null, true);
}
done()
};
RoleController.js
const express = require('express')
const router = express.Router()
const authorize = require('helpers/authorize')
router.post('/create', authorize('Admin'), createRole)
module.exports = router
function createRole(req, res, next)
{
//role creation code goes here
}
到目前为止,一切正常,当使用令牌请求create
路由时,authorize.js
正在检查令牌是否有效,并在检查用户角色是否与路由角色匹配之后(例如{ {1}})
现在,问题出在这里
我正在尝试将admin
移至authorize
中的中间件。然后根据通过RoleController.js
的请求路由,从database
获得对模块的访问权限
req.originalUrl
更改为此后,它无法正常工作。流程转到var isAuthorized = function (req, res, next)
{
authorize(req.originalUrl) // just trying to check the authorization as a first level and moving forward to route only if authorized
next();
}
router.post('/create', createRole) //Removed authorize here
函数,但未调用authorize
函数。
可能是由于_isRevoked
中的async
所致,但我被困在此处继续进行。有什么想法吗?