我想要保护我的express应用程序中的一些端点,如果我的应用程序变成一个大的app...now,我想创建一些简单的东西来管理我正在做的事情是这样的:
setProtected(router) {
const self = this;
router.use(this.auth);
...
}
setPublic(router) {
const self = this;
...
}
getRouter() {
const router = express.Router();
this.setPublic(router);
this.setProtected(router);
return router;
}
通过以下方式:
auth(req, res, next) {
if(req.isAuthenticated()) {
console.log('req.isAuthenticated()', req.isAuthenticated());
return next();
}
return res.send(401);
}
这种情况下的问题是很难维护,并且不能很好地工作,例如,如果我的publicRoute中有/:id,例如,当我没有登录时,在受保护的路由中有/ my -items,并且我试图访问/ my -items,我得到的代码是/:id。
另一个想法是用我的所有urls列表创建一个json,这些urls具有相同的信息,如受保护/不受保护和最终角色,然后使用以下内容更改auth:
import urls from './urls';
auth(req, res, next) {
if (urls[req.url] == 'public') {
return next()
}
else if (urls[req.url] == 'protected' && req.isAuthenticated()) {
return next();
}
return res.send(401);
}
对你来说最好的方法是什么?
发布于 2018-03-18 22:07:38
const authenticate = (req, res, next) {
.. some auth logic
next();
}
app.use('/', main...
app.use('/profile', authenticate, otherMiddleware,
app.use('/admin', authenticate, isAdmin, otherMiddleware...
发布于 2020-10-29 19:57:37
在您的主文件(server.js)中,导入路由并使用其中的中间件:)
server.js
const express = require('express')
const cors = require('cors')
const app = express()
// import admin routes
const adminRoute = require('./app/routes/admin.route.js')
// Add middleware for parsing URL encoded bodies (which are usually sent by browser)
app.use(cors())
// Add middleware for parsing JSON and urlencoded data and populating `req.body`
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
// homepage route
app.get("/", (req, res) => {
res.json({ message: "Hello World" })
})
// restricted by middleware "isAdmin"
app.use('/api/v1', isAdmin, adminRoute)
app.listen(8008).on('listening', () => {
console.log('Server is running on 8008')
})
admin.route.js
const express = require('express')
const admin = require('../controllers/admin.controller.js')
const router = express.Router()
// get all admin users
router.get('/users', (req, res, next) => {
admin.getAdminUsers(req, res, next)
})
module.exports = router
https://stackoverflow.com/questions/49348465
复制相似问题