示例:公网api不需要鉴权,内网路由需要通过中间件鉴权。但是我们如何区分传入的http请求是公共的还是私有的?
发布于 2020-03-09 00:59:19
如果你正在使用Express,有很多选择。一个简单的设计选择是将您的私有API放在具有中间件的路由器上,该路由器在路由到任何路由之前检查身份验证,并将公共API放在没有中间件检查的路由器上。然后,Express中内置的路由器机制和路由器上适当放置的需要身份验证的中间件将为您完成所有工作。
下面是一个简单的例子:
const express = require('express');
const app = express();
const routerAuth = express.Router();
const routerPublic = express.Router();
// check auth here in the routerAuth router as the first route definition in that router
routerAuth.use((req, res, next) => {
// check auth here
if ( /* code here to check authorization */) {
next();
} else {
// not authorized
res.status(401).send("Not authorized");
// or maybe just res.redirect("/login");
}
});
// routers on routerAuth
routerAuth.get("/seeEverything", ...)
routerAuth.get("/admin", ...)
// routes on routerPublic
routerPublic.get("/", ...);
routerPublic.get("/login", ...);
routerPublic.get("/signup", ...);
// hook the routers into our server
// specify the public router first so they get a chance to be matched
// before routerAuth enforces authentication
app.use(routerPublic);
app.use(routerAuth);
app.listen(80);将这些路由器中的每一个放入它们自己的模块中然后导入它们是很常见的,但为了简单起见,我在这里跳过了这一部分。此示例显示每个路由器共享相同的路径命名空间,但如果需要,您也可以将专用路由器放在其自己的路径前缀上。
https://stackoverflow.com/questions/60589809
复制相似问题