gpt4 book ai didi

node.js - 使用身份验证中间件安排路由

转载 作者:太空宇宙 更新时间:2023-11-03 23:04:24 25 4
gpt4 key购买 nike

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

它们在这里:

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. 假设我没有公共(public)路线。

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

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

这会起作用。这使得所有安全路由都安全,但它阻止我访问公共(public)路由('/:id')。

2.我可以将公共(public)路线移至顶部:

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

那么,还有我没有考虑过的更好选择吗?什么被认为是最佳实践?

谢谢

最佳答案

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

另一个选项是使用 HTTP 身份验证,例如 .htaccess。看看https://github.com/http-auth/http-auth .

我之前进行身份验证的一种方法是将用户名/密码作为 json 通过请求正文传递一次,然后为将来的请求生成无状态 token ( https://github.com/auth0/node-jsonwebtoken )。就我而言,没有多少路由器条目需要身份验证,因此我在条目本身上进行了处理。

此外,为了提高安全性,请使用 HTTPS 或对您的数据进行编码。例如。 How to create an HTTPS server in Node.js?

希望对您有帮助!

关于node.js - 使用身份验证中间件安排路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39218504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com