Javascript 如何通过passport.js链传递参数?

Javascript 如何通过passport.js链传递参数?,javascript,passport.js,Javascript,Passport.js,我正在使用passport.js对用户进行身份验证。我希望能够传递从用户收集的用户名,该用户名将到达身份验证过程的末尾,以便在创建用户时存储用户名(如果该用户名尚不存在)。我试过这个: app.get("/auth/google", function(request, response) { console.log(request.query.username); passport.authenticate("google", { scope:

我正在使用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的调用打印用户名,但回调打印未定义的用户名。即使我能把用户名输入回叫,我仍然不确定如何将它输入谷歌的策略。然后我是否必须创建自己的策略才能使其工作?

您可以将状态对象传递给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并在回调中对其进行解析。

对于使用OpenID的任何人,req.query似乎被OpenID查询参数覆盖,因此无法直接传递。但是,您可以将变量附加到req.session

router.get('/auth/social', (req, res, next) => {
  req.session.foo = req.query.foo;
  next();
}, passport.authenticate('social'));
不要忘记在策略选项中包含passReqToCallback标志:

{
  passReqToCallback: true,
  returnURL: config.app.returnUrl,
  realm: config.app.realm,
  apiKey: config.app.apiKey
}

会话和cookie也可能被OpenID策略()覆盖?我尝试过你的解决方案,但是
req.session.foo
在回调路径中是
未定义的
。关于这个问题有很多问题,但在我看来这是最重要的答案!谢谢@基里佐