express-jwt - 显示调试权限
express-jwt - Show permission for debug
可能会在错误中间件中显示需要哪些权限?
//User don't have this permission
app.post("/", guard.check(permissions.$("admin")), (req, res) => {
return new Area(req.body)
.save()
.then(area => {
///....
})
.catch(err => next(err))
})
错误中间件
我想在 console.log()
中显示许可
app.use(function (err, req, res, next) {
if (err.code === "invalid_token") {
return res.status(401).send("...")
}
if (err.code === "credentials_required") {
return res.status(401).send("...")
}
//...
})
可以将guard.check
中间件包装到另一个中间件中,将需要的权限放到req
对象中,然后在error handler中间件中获取即可。
const customGuard = (permissions) => { // middleware factory
return (req, res, next) => { // return a middleware function
req.requiredPermissions = permissions; // store `permissions` in `req.requiredPermissions`
guard.check(permissions)(req, res, next); // check your permissions with express-jwt-permissions's guard
}
}
用法,替换
app.post("/", guard.check(permissions.$("admin"))
...
来自
app.post("/", customGuard(permissions.$("admin"))
...
然后,在你的错误中间件
app.use(function (err, req, res, next) {
console.log("Required permissions: ", req.requiredPermissions); // here
if (err.code === "invalid_token") {
return res.status(401).send("...")
}
if (err.code === "credentials_required") {
return res.status(401).send("...")
}
//...
})
可能会在错误中间件中显示需要哪些权限?
//User don't have this permission
app.post("/", guard.check(permissions.$("admin")), (req, res) => {
return new Area(req.body)
.save()
.then(area => {
///....
})
.catch(err => next(err))
})
错误中间件
我想在 console.log()
中显示许可app.use(function (err, req, res, next) {
if (err.code === "invalid_token") {
return res.status(401).send("...")
}
if (err.code === "credentials_required") {
return res.status(401).send("...")
}
//...
})
可以将guard.check
中间件包装到另一个中间件中,将需要的权限放到req
对象中,然后在error handler中间件中获取即可。
const customGuard = (permissions) => { // middleware factory
return (req, res, next) => { // return a middleware function
req.requiredPermissions = permissions; // store `permissions` in `req.requiredPermissions`
guard.check(permissions)(req, res, next); // check your permissions with express-jwt-permissions's guard
}
}
用法,替换
app.post("/", guard.check(permissions.$("admin"))
...
来自
app.post("/", customGuard(permissions.$("admin"))
...
然后,在你的错误中间件
app.use(function (err, req, res, next) {
console.log("Required permissions: ", req.requiredPermissions); // here
if (err.code === "invalid_token") {
return res.status(401).send("...")
}
if (err.code === "credentials_required") {
return res.status(401).send("...")
}
//...
})