How do I use a wildcard in JWT unless?

情到浓时终转凉″ 提交于 2019-12-12 14:02:12

问题


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}) );

回答1:


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.




回答2:


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 }));


来源:https://stackoverflow.com/questions/38821632/how-do-i-use-a-wildcard-in-jwt-unless

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!