在具有不同用户角色的 passport-jwt 中设置身份验证很热吗?

Hot to set authentication in passport-jwt with different role of user?

我正在尝试添加一个名为 admin 的角色来验证登录到仪表板 Web 应用程序的管理员,而普通用户只能访问常规页面。

对于普通用户,我需要 server.js 中的护照

// use passport 
app.use(passport.initialize());
require("./config/passport")(passport);

config/passport.js中,像官方例子中的代码,我这样试试:

const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
const mongoose = require('mongoose');
const User = mongoose.model("users");
const key  =require("../config/key");

const  opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = key.secretKey;

module.exports = passport => {
    passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
        // console.log(jwt_payload);
        User.findById(jwt_payload.id)
            .then(user => {
                if(user) {
                    return done(null, user);
                }

                return done(null, false);
            })
            .catch(err => console.log(err));
    }));
};

这种方式很好,我在路线中使用了它们

router.get("/current", passport.authenticate("jwt", {session: false}), (req, res) => {
    res.json({
        id: req.user.id,
        name: req.user.name,
        username: req.user.username,
        email: req.user.email,
        avatar: req.user.avatar,
    });
}) 

但是,当我在令牌规则中添加角色时:

const rule = {id:admin.id, email: admin.email, avatar: admin.avatar, admin: admin.admin};

我如何检查管理员 属性 是否为 true 以查询 passport.js

中的不同集合

我试过了,这对我不起作用,错误似乎是服务器 运行 两次:

module.exports = passport => {
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
    // console.log(jwt_payload);
    if(jwt_payload.admin){
        Admin.findById(jwt_payload.id)
        .then(user => {
            if(user) {
                return done(null, user);
            }

            return done(null, false);
        })
        .catch(err => console.log(err));
    } else {
    User.findById(jwt_payload.id)
        .then(user => {
            if(user) {
                return done(null, user);
            }

            return done(null, false);
        })
        .catch(err => console.log(err));
    }
}));};

错误是: Error

这是我所做的并且效果很好...我只是将 isAdmin: Boolean 包含在我的用户模型中,如下所示:

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 50
  },
  email: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 255,
    unique: true
  },
  password: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 1024
  },
  isAdmin: Boolean
});

然后像这样将其包含在 jwt 中:

userSchema.methods.generateAuthToken = function() { 
  const token = jwt.sign({ _id: this._id, isAdmin: this.isAdmin }, config.get('jwtPrivateKey'));
  return token;
}

然后自定义中间件来检查 isAdmin 的值,如下所示:

module.exports = function (req, res, next) { 
  if (!req.user.isAdmin) return res.status(403).send('Access denied.');
  next();
}

然后我简单地导入它并将它用作任何路由的第二个参数,如下所示:

router.patch('/:id', [auth, isAdmin, validateObjectId], async (req, res) => {
  // handle the route (in order to do anything in this route you would need be an admin...)
});

编辑:如果您对此处的其他两个中间件感到好奇,它们是...

auth.js:

const jwt = require('jsonwebtoken');
const config = require('config');

module.exports = function (req, res, next) {
  const token = req.header('x-auth-token');
  if (!token) return res.status(401).send('Access denied. No token provided.');

  try {
    const decoded = jwt.verify(token, config.get('jwtPrivateKey'));
    req.user = decoded; 
    next();
  }
  catch (ex) {
    res.status(400).send('Invalid token.');
  }
}

验证对象 ID:

const mongoose = require('mongoose');

module.exports = function(req, res, next) {
  if (!mongoose.Types.ObjectId.isValid(req.params.id))
    return res.status(404).send('Invalid ID.');

  next();
}