gpt4 book ai didi

node.js - 热衷于在 Passport-jwt 中设置具有不同用户角色的身份验证?

转载 作者:太空宇宙 更新时间:2023-11-03 23:17:31 25 4
gpt4 key购买 nike

我正在尝试添加一个名为 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));
}));
};

这种方式效果很好,我在 route 使用它们

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,
});
})

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

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

最佳答案

这就是我所做的,它运行得很好...我只需在我的用户模型中包含 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();
}

关于node.js - 热衷于在 Passport-jwt 中设置具有不同用户角色的身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53522307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com