gpt4 book ai didi

javascript - 我想了解passport js如何工作,特别是req.user以及数据如何填充

转载 作者:行者123 更新时间:2023-12-01 02:40:51 25 4
gpt4 key购买 nike

我是 Node js 的新手,尝试过使用 Passport 进行身份验证,但我发现很难理解工作流程。所以我的问题是 req.user 它实际上来自哪里?它是与 Passport 相关的常量吗,不能更改为其他任何内容,例如 req.profile

其次是下面的html代码

  <p>
<strong>id</strong>: <%= user._id %><br>
<strong>username</strong>: <%= user.local.username %><br>
<strong>password</strong>: <%= user.local.password %>
</p>

从 html 填充 user 对象的地方,我的数据库架构和我的 Passport 都不包含单词 user

这是我的数据库架构

  local:{
username : String,
password : String
}

谢谢

最佳答案

我会告诉你在哪里req.user来自不使用 Passport 。您需要了解的第一件事是 middleware在express中只是一个接受request的函数, response和一个 next function .

假设我有一个端点:

发布/auth/login这需要 usernamepassword .

此端点可能返回 access token (由您生成并存储在数据库中的随机字符串,如果您不想存储在数据库中,可以查看 JWT)。

好的,现在您在登录成功后就拥有了该访问 token 。

您可以将其与其他请求一起传递到您的服务器。让我们说另一个端点:

获取/auth/profile它受到保护,只能通过权限 access token 访问.

但是什么是保护路由呢?这是middleware .

下面我们定义一个checkAuth中间件。

function checkAuth(req, res, next) {
// here I can retrieve accessToken from the request header
const accessToken = req.get('accessToken')
// with this accessToken I can query the database and check if this access token is correct or not
findUserWithTheAccessToken(accessToken)
.then(user => {
if (user) {
// Here's the answer to your question where `req.user` comes from.
req.user = user
next() // call next() so it can go to the request handler
} else {
throw new Error('Invalid access token.')
}
})
}

// then your router would look something like the following
router.get('/auth/profile', checkAuth, handler) // implement your handler ☺️

您可以随时查看 express 网站了解更多信息。

关于javascript - 我想了解passport js如何工作,特别是req.user以及数据如何填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47575234/

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