代码之家  ›  专栏  ›  技术社区  ›  lonix

仅使用Express JWT保护某些路线

  •  1
  • lonix  · 技术社区  · 7 年前

    我有“公共”路由和“API”路由,应该由 express-jwt .

    // define public routes in a router
    const routerPublic = express.Router();
    routerPublic.route("/login", (req, res) => /* whatever */);
    routerPublic.route("/about-us", (req, res) => /* whatever */);
    routerPublic.route("/foo/bar/baz", (req, res) => /* whatever */);
    
    // define API routes in a router
    const routerApi = express.Router();
    routerApi.route("/api/v1/foo", (req, res) => /* whatever */);
    routerApi.route("/api/v1/bar", (req, res) => /* whatever */);
    
    // add routers to express app
    app.use(routerPublic);                                 // (1)
    app.use(routerApi, jwt({ secret: "secret" }));         // (2)
    

    所以我填充了两个 express.Router 实例-一个具有不安全的路由,另一个具有安全的路由。然后我将这些路由器加载到Express应用程序中,只有安全的路由才需要进行身份验证。

    但是顺序很重要。如果第(1)行在第(2)行之前,则按预期工作。但是,如果(2)在(1)之前,那么所有的东西都会经过身份验证,包括安全和不安全的路由。

    所以有一个比赛条件,我不明白。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Shay Moshe    7 年前

    把它作为答案发布,以帮助他人,

    您使用新的快速路线,可以尝试以下方法吗:

    routerApi.use(jwt({ secret: "secret" }))
    
    推荐文章