Closed iamnotstone closed 5 years ago
sorry for this question. I figure out myself. I write a middleware to do those things together:
/*middleware/acl.js */
export function checkRoleWithPassport(roles, passport, strategy, opts){
return function(req, res, next){
passport.authenticate(strategy, opts, function(err, user, info){
if(err) res.status(403).send('forbidden')
else if(!user) res.status(403).send('forbidden')
else{
if(roles.length == 0)
next()
else if(roles.includes(user.role))
next()
else
res.status(403).send('forbidden')
}
})
}
}
/* route/index.js */
app.get('/myapi', checkRoleWithPassport(['manager'], passport,
'jwt', {session, false}), function(req, res){
...
}) // this should only allow the 'manager' to access /myapi
Closing
app.get('/myapi', checkRoleWithPassport(['manager'], passport, 'jwt', {session, false}), function(req, res){
can you post your passport.js strategy file ? i can't get your idea to work route not respoinding the only thing i see if i console.log before passport.authenticate
in acl.js
I am using passport-jwt. And I'm trying to implement an acl pattern in my system . There are some different roles in my system. And I want to control their access to some resource. I think the common way to do that in token based authentication is to write a middleware for express.js which will validate the token and add a 'role' field to 'req.user'. And then mount another middleware for every route which will specify which roles can access them. So my question is , How to combine this approach with passport-jwt .
plus: The common way of using passport-jwt strategy :
The common way I think in token based authentication:
and at every route: