代码之家  ›  专栏  ›  技术社区  ›  Hary

授权中间件功能

  •  0
  • Hary  · 技术社区  · 6 年前

    我正试图在 node.js

    授权.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()
    };
    

    角色控制器.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 正在检查令牌是否有效,并在检查用户角色是否与路由角色匹配(例如。 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
    

    授权 函数,但它不调用 _isRevoked

    可能是因为 async 在里面 但我被困在这里继续。有什么想法吗?

    0 回复  |  直到 6 年前
    推荐文章