我正在使用 passport.js 对用户进行身份验证。我希望能够传递从用户那里收集的用户名,这将到达身份验证过程的末尾,以便我可以在创建用户时存储用户名(如果它尚不存在)。我试过这个:
app.get("/auth/google", function(request, response)
{
console.log(request.query.username);
passport.authenticate("google",
{
scope:
[
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email"
]
})(request, response);
});
app.get("/auth/google/callback", function(request, response)
{
console.log(request.query.username);
passport.authenticate("google",
{
successRedirect: "/",
failureRedirect: "htm/error"
})(request, response);
});
对/auth/google 的调用打印用户名,但回调打印未定义。即使我可以将用户名获取到回调,我仍然不确定如何将其获取到 google 策略。然后我是否必须制定自己的策略才能使其发挥作用?
最佳答案
您可以将一个state 对象传递给 passport.authenticate,如下所示:
passport.authenticate("google",
{
scope:
[
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email"
],
state: request.query.username
})(request, response);
您可以通过req.query.state 访问状态。
用户名应该是一个字符串,而不是一个对象。如果要在状态中存储对象,请先调用 JSON.stringify 并在回调中对其进行解析。
关于javascript - 如何通过我的 passport.js 链传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13670217/