根据express-jwt官方说明文档,我们可以在总路由上加上jwt验证,同时在那些不想加验证的路由上使用unless
去除验证,如下:
app.use(jwt({ secret: 'shhhhhhared-secret'}).unless({path: ['/token']}));
这样就不用每条路由挨个去加jwt验证了,方便了不少。但是在使用过程中发现一个问题:这个unless
无法区分http-method, 那么象以下这样的路由:
router.route('/')
/** GET /api/users - Get list of users */
.get(userCtrl.list)
/** POST /api/users - Create new user */
.post(validate(paramValidation.createUser), userCtrl.create);
我只想在路由的get方法上做验证,post方法时注册方法,不能添加验证(否则就无法注册了)。像这样的官网没有说明,google全网也没有找到解决方法。最后还是翻源码找到了解决方法:
在express-jwt源码的index.js文件中找到这样一句:
var unless = require('express-unless');
...
/*express-jwt/index.js*/
middleware.unless = unless;
说明它用的是express-unless
,再看package.json
,也证实了这一点
/*express-jwt/package.json*/
"dependencies": {
"async": "^1.5.0",
"express-unless": "^0.3.0",
"jsonwebtoken": "^8.1.0",
"lodash.set": "^4.0.0"
},
上express-unless repo找到示例:
app.use(requiresAuth.unless({
path: [
'/index.html',
{ url: '/', methods: ['GET', 'PUT'] } //正是我需要的!
]
}))
最后完成:
app.use(
"/api",
jwt({ secret: config.jwtSecret }).unless({
path: [
{ url: '/api/auth/login', methods: ['POST']},
{url: '/api/users', methods: ['POST']},
{url: '/api/test', methods: ['GET']}
]
}),
routes
);
问题解决,源码是最权威的!