授权中间件功能

时间:2018-12-21 11:51:00

标签: node.js express middleware express-jwt

我正在尝试在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所致,但我被困在此处继续进行。有什么想法吗?

0 个答案:

没有答案