使用身份验证中间件

时间:2016-08-30 03:54:01

标签: node.js routes

我有很多路线。 其中大多数都需要身份验证 一个没有。

他们是:

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

1。让我们想象一下,我没有公共路线。

在页面顶部,我可以放一个安全检查中间件,一切都很好。 它只会通过安全连接,并将重定向非安全。

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) {...})

但是这样它可以捕获我的所有请求,并且所有安全路径都无法访问。

3。我可以在每条安全路线上放置一个中间件,但这似乎有点单调乏味,容易出现人为错误:

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

那么,有没有更好的选择我没有考虑过?什么是最佳做法?

谢谢

2 个答案:

答案 0 :(得分:2)

Out of your options I would personally prefer the first one. In the middleware you can always check on req.path or req.url to choose what to set as secure.

Another option is using HTTP authentication like in .htaccess. Have a look at https://github.com/http-auth/http-auth.

A way I have done authentication before was by passing username/password over the request body as json once and then producing a stateless Token for future requests (https://github.com/auth0/node-jsonwebtoken). In my case not many router entries needed authentication, so I handled it on the entries themselves.

Also, for extra security, use HTTPS or encode your data. Eg. How to create an HTTPS server in Node.js?

Hope it helped!

答案 1 :(得分:1)

如果/:id应与特定模式匹配,例如MongoDB ObjectId,则可以使匹配更具体,因此它与其他路线不匹配:

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

如果你想匹配ObjectId的,你可以使用它:

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

更多信息herepath-to-regexp是Express用于执行网址匹配的模块。)