node.js - 如何在 polka js 中保护路由
问题描述
我正在尝试使用 polka js 实现受保护的路由。我尝试使用中间件来实现它,但即使对于未受保护的路线,我也不断获得未经授权的许可。
const polka = require('polka');
const send = require('@polka/send-type');
const app = polka();
app.get('/un-protected', (req, res) => {
return send(res, 200, {
msg: 'Unprotected route',
});
});
const auth = false;
app
.use((req, res, next) => {
if (auth) {
next();
} else {
return send(res, 401, {
errors: {
msg: 'unauthorized',
},
});
}
})
.get('/protected', (req, res) => {
return send(res, 200, {
msg: 'Protected route',
});
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
预期的行为是只有 '/protected' 路由应该显示未经授权的消息,但目前即使对于 '/un-protected' 路由,未经授权的消息也会不断弹出。
解决方案
认证检查应该放在指定的路由和去保护路由时的动作之间。
app.get('/un-protected', (req, res) => {
return send(res, 200, {
msg: 'Unprotected route',
});
});
const auth = false;
const checkAuth = (req, res, next) => {
if (auth) {
next();
} else {
return send(res, 401, {
errors: {
msg: 'unauthorized',
},
});
}
}
app
.get('/protected', checkAuth, (req, res) => {
return send(res, 200, {
msg: 'Protected route',
});
});
推荐阅读
- java - 超过时间限制:BFS
- android-studio - Android 11 sdk 30 上的 Okhttp 异常 java.lang.AssertionError
- angular - 使用库中声明的角度组件时出错
- html - 如何使选择列表出现在另一个元素上?
- node.js - React 17.0.1 基本 onChange 没有将值更新为状态
- visual-studio - Visual Studio 2019 中的 m_msgCur
- javascript - 为什么对象保留其继承的属性?
- apache - 活动 mpm_event 时的 ERR_EMPTY_RESPONSE
- kubernetes - 如何在 BareMetal -KinD 中使用 LoadBalancer?
- python - Python List插入独立的参考变量