安排路由与authentication中间件

我有很多路线。 他们大多需要authentication。 一个不。

他们来了:

router.get('/secure1', function (req,res) {...}) router.get('/secure2', function (req,res) {...}) router.get('/secure3', function (req,res) {...}) router.get('/:id', function (req,res) {...}) 

假设我没有公共路线。

在页面的顶部,我可以把一个安全检查中间件,一切都很好。 它只会让安全的连接,并将redirect非安全。

 router.use(function (req,res,next) { securityCheck() next() }) router.get('/secure1', function (req,res) {...}) router.get('/secure2', function (req,res) {...}) router.get('/secure3', function (req,res) {...}) router.get('/:id', function (req,res) {...}) 

这将工作。 这使所有的安全路线安全,但它阻止我从公共路线('/:id')。

2.我可以把公共路线移到顶端:

 router.get('/:id', function (req,res) {...}) router.use(function (req,res,next) { securityCheck() next() }) router.get('/secure1', function (req,res) {...}) router.get('/secure2', function (req,res) {...}) router.get('/secure3', function (req,res) {...}) 

但是这样它就捕获了我所有的请求,所有的安全path都无法访问。

3.我可以在每条安全路线上放置一个中间件,但是这看起来有点乏味,并且容易出现人为错误:

 router.get('/secure1',securityCheck(), function (req,res) {...}) 

那么,有没有更好的select我没有考虑? 什么被认为是最好的做法?

谢谢

出于你的select,我个人更喜欢第一个。 在中间件中,您可以始终检查req.pathreq.url以select要设置为安全的设置。

另一种select是使用HTTP身份validation,如.htaccess。 看看https://github.com/http-auth/http-auth

我之前完成身份validation的一种方式是通过在请求主体上传递用户名/密码作为json一次,然后为将来的请求生成一个无状态令牌( https://github.com/auth0/node-jsonwebtoken )。 在我的情况下,没有太多的路由器条目需要身份validation,所以我在条目本身处理它。

而且,为了获得额外的安全性,请使用HTTPS或编码您的数据。 例如。 如何在Node.js中创build一个HTTPS服务器?

希望它有帮助!

如果/:id应该匹配一个特定的模式,比如一个MongoDB的ObjectId ,你可以使匹配更具体,所以它不会匹配其他路由:

 router.get('/:id([a-fA-F0-9]{24})', function (req,res) {...}) 

如果你想匹配ObjectId的没有,你可以使用这个:

 router.get('/:id(|[a-fA-F0-9]{24})', ...); 

这里有更多的信息(Express path-to-regexp是Express用于执行URL匹配的模块)。