基于角色的 jwt 授权 [英] Role based jwt authorization
问题描述
我正在尝试使用 JSON Web 令牌对 Node.js API 进行身份验证.我可以生成令牌对用户进行身份验证.现在我需要根据用户角色保护我的 API.这是我如何路由中间件以进行身份验证和检查令牌.
I am trying to authenticate a Node.js API with JSON Web Tokens. I could generate the token authenticate the users. Now I need to proptect my API based on the user roles. Here is how I route middleware to authenticate and check token.
var app = express();
var apiRoutes = express.Router();
apiRoutes.use(function (req, res, next) {
var token = req.body.token || req.param('token') || req.headers['x-access-token'];
if (token) {
jwt.verify(token, app.get('superSecret'), function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
apiRoutes.get('/check', function (req, res) {
//...
});
app.use('/api', apiRoutes);
这样,我保护 API 说 /api/check
.这只能由 admin 用户
访问.现在我有另一个 super user
可以访问 /api/validate
而 admin user
无法访问.如何仅为 超级用户
保护 /api/validate
.我是否需要再编写一个中间件来执行此操作?
This way, I protect the API say /api/check
. This can be accessed by admin user
only. Now I have another super user
who can access /api/validate
which the admin user
can't access. How can I protect /api/validate
only for super user
. Do I need to write one more middleware to do this?
这是我现在进行管理员检查的方法,
Here is how I do the admin check now,
apiRoutes.post('/delete/:id',requireAdmin, function (req, res) {
//do the rest
};
function requireAdmin(req, res, next) {
var currentUserRole=".."; //get current user role
if('admin' == currentUserRole )
{
next();
}
else{
next(new Error("Permission denied."));
return;
}
};
类似 requireSuperUser
功能用于超级用户检查.这是进行管理员/超级用户检查的正确方法吗?
Similarly requireSuperUser
function for super user check.Is this the right way to do admin/super user check?
推荐答案
创建 JWT 时,您可以提供自己的有效负载作为私有声明.例如:
When creating the JWT, you can provide your own payload as a private claim. E.g.:
{
"sub": "1234567890",
"name": "John Doe",
"admin": true,
"superUser": false
}
同样的方式,您也许可以为登录用户列出一组用户角色
Same way you can perhaps list a set of user roles for the logged in user
{
"sub": "1234567890",
"name": "John Doe",
"roles": [
"ADMIN",
"SUPERUSER"
]
}
然后需要对令牌进行解码(最好使用 express.js 中间件进行此身份验证/授权)并检查角色并在不允许时抛出 HTTP 401.如果允许,调用 next();
继续输入匹配的路由.
What is required then is to decode the token (best use express.js middleware for this authentication/authorization purpose) and check the roles and throw a HTTP 401 when it's not allowed. When it's allowed, call next();
to go ahead and enter the matching route.
这种可能的中间件功能的小例子:
Small example of such a possible middleware function:
function canAccess(req, res, next) {
checkAuthorization(req, function (err, authorized) {
if (err || !authorized) {
res.send({message: 'Unauthorized', status: 401});
}
next();
});
function checkAuthorization(req, callback) {
// jwt decode and actual authentication admin/superuser matching goes here..
}
}
router.use(canAccess);
有关 JWT 声明的更多信息:https://jwt.io/introduction
For more information on JWT claims: https://jwt.io/introduction
有关 expressjs 中间件的更多信息:https://expressjs.com/en/guide/using-middleware.html
For more information on expressjs middleware: https://expressjs.com/en/guide/using-middleware.html
这篇关于基于角色的 jwt 授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!