如何在 nodejs 中保护路由
如何在 nodejs 中保护路由
请问我怎样才能让管理员访问特定的路线
这是我的 mongodb 数据库
{
"_id": {
"$oid": "640e16b3186c0b1910c1dedf"
},
"isAdmin": true,
"name": "sample name",
"email": "[email protected]",
"password": "$2a$10$tbi9fblLS9NXai3Osb7H7OdLVqq34I0OTKgvB5BmVBEASabvX/ybu",
"__v": 0
}
isAdmin 设置为 true 我希望管理员是唯一访问此路由的人
router.post(`/categories`, async (req, res) => {
if(req.body.isAdmin){
try {
let category = new Category();
category.type = req.body.type;
category.description = req.body.description;
await category.save();
res.json({
status: true,
message: "save succes"
});
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}}
else{
console.log("auth")
}
});
每次我尝试上面的代码时,它都会跳过 if 语句并转到 else
回答如下:如果您正在访问
req.body.isAdmin
这意味着您发布请求正文 json 必须包含属性 isAdmin
并设置为 true
:
例如
const postRequestBody = {
isAdmin: true
}
这不安全,因为客户端可以控制是否显示管理员访问权限。
在您的实施之后,您应该在 else 子句中返回 HTTP 401 Unauthorized。
router.post(`/categories`, async (req, res) => {
if(req.body.isAdmin){
try {
let category = new Category();
category.type = req.body.type;
category.description = req.body.description;
await category.save();
res.json({
status: true,
message: "save succes"
});
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
} else {
res.status(401).json({ success: false, message: "Sorry, you need admin access for this route" }
console.log("auth")
}
});
最新文章
- 物权法全文内容有哪些呢
- zigbee初级教程(零) :cc2530开发环境搭建
- 综艺节目php灭灯
- spark web ui中的skipped的含义
- Pytorch、TorchVision、Python、Jetpack版本匹配问题
- Android出现没有资源包问题,Android打包出现的小问题汇总
- 统计学之大数定律、小数法则
- Linuxmmap
- C++:指针:void*指针(跳跃力未定的指针)
- 商餐网
- 【网络流量监控工具之Nethogs】
- 终于有个高效率的排列组合算法
- Mysql与Postgresql常用命令比较
- SpringSecurity原理:探究SpringSecurity运作流程
- java鬼混笔记:springboot 5、springboot的Scheduled定时器:fixedDelay和fixedRate区别
- pgpool分析三
- 了解Intel IPP
- MFC 的CList,CPtrList,CObList,CStringList 的用法之CList
- SQL——DDBC手册
- LOCALDB