我有很多路线。 其中大多数都需要身份验证 一个没有。
他们是:
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) {...})
那么,有没有更好的选择我没有考虑过?什么是最佳做法?
谢谢
答案 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})', ...);
更多信息here(path-to-regexp
是Express用于执行网址匹配的模块。)