Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a wildcard in JWT unless?

I'm using express-jwt to secure my node application, and am wondering how I can use a wildcard in the unless parameter. My working code is below, what I'd really like to do is open up access to anything that has a path starting with '/login' so I don't have to list every single resource. When I add '/login*' to the unprotected array it ends up blocking /login with a 401/unauthorized.

Works:

// routes open to all
var unprotected = [
  '/login',
  '/login/app/main.js',
  'favicon.ico'
];

// configure jwt
var jwtCheck = jwt({
  secret: new Buffer(config.get('auth0.secret'), 'base64'),
  audience: config.get('auth0.clientid')
});

// insert jwt middleware
app.use( jwtCheck.unless({path: unprotected}) );

Doesn't work:

// routes open to all
var unprotected = [
  '/login*',
  'favicon.ico'
];

// configure jwt
var jwtCheck = jwt({
  secret: new Buffer(config.get('auth0.secret'), 'base64'),
  audience: config.get('auth0.clientid')
});

// insert jwt middleware
app.use( jwtCheck.unless({path: unprotected}) );
like image 384
Graham Avatar asked Aug 08 '16 05:08

Graham


2 Answers

The regexp needs to exist outside the quotes:

var unprotected = [
  /\/login*/,
  /favicon.ico/
];

Note that at this time with express-unless you can't mix regexp and strings in the same config array, which is why the second argument needs to have forward slashes instead of quotes.

like image 185
Graham Avatar answered Sep 19 '22 19:09

Graham


You can use a path-to-regexp and you will no need to write those ugly regExps by your own.

Sample below:

const pathToRegexp = require('path-to-regexp');

// Use JWT auth to secure the API
const unprotected = [
    pathToRegexp('/login*'),
    pathToRegexp('/favicon.ico')
];

app.use(expressJwt({ secret: config.tokenSecret }).unless({ path: unprotected }));
like image 29
Null Avatar answered Sep 20 '22 19:09

Null