我正在尝试添加一个名为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};
如何检查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
答案 0 :(得分:2)
这是我的工作,并且效果很好...我将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.');
}
}
validateObjectId:
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();
}