Skip to content

Using krakenjs middleware config for whitelisting and blacklisting routes

Matt Edelman edited this page Apr 14, 2015 · 10 revisions

Whitelisting

Routes under a single namespace

Building from the kraken-js default of mounting routes from /routes/index.js:

  • the lib/auth module (see here) will check authentication before the built-in router for all /auth/* routes.
  • Any protected routes will be mounted via /routes/auth.js (see here)
{
  "middleware": {
    "auth": {
      "enabled": true,
      "priority": 119, // just before the built-in router
      "route": "/auth",
      "module": {
        "name": "path:./lib/auth",
        "arguments": [ "admin", "password" ]
      }
    },
    "auth-router": {
      "enabled": true,
      "priority": 121, // just after the build-in router
      "route": "/auth",
      "module": {
        "name": "express-enrouten",
        "arguments": [{ "index": "path:./routes/auth" }]
      }
    }
  }
}

Any routes defined under different namespaces will not require authentication per this configuration.

Try it yourself

Clone middleware-patterns and run the whitelist pattern.

Blacklisting

The blacklist pattern relies on the way express builds its route-map, internally. Each route you define is converted to an equivalent RegExp by means of the path-to-regexp module. We can exploit this fact to build a route with one or more negative lookaheads:

"middleware": {
  "auth": {
    "priority": 119,
    "enabled": true,
    "route": "\/((?!$))((?!login))((?!logout))*", //run on every route EXCEPT /login and /logout
      "module": {
        "name": "path:./lib/auth"
      }
    },

warning

If you use the blacklist pattern, verify the generated regex is what you want. You can generate the regex with [email protected] and check it against a regex visualizer like regulex. Don't forget about optional trailing slashes.

Try it yourself

Clone middleware-patterns and run the blacklist pattern.