使用 express-jwt 只保护一些路由

Secure only some routes with express-jwt

我有 "public" 个路由,"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) 之前出现,那么所有内容都会经过身份验证,包括安全和不安全的路由。

所以有一个竞争条件,我不明白。

将其作为答案发布以帮助他人,

你使用的是新的快速路线,你能试试这样吗:

routerApi.use(jwt({ secret: "secret" }))