javascript - 如何通过我的 passport.js 链传递参数?

标签 javascript passport.js

我正在使用 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/

相关文章:

javascript - 将 Rails DB as_json.to_json 嵌入到 Javascript 中不起作用。 (变成“东西”)

javascript - 在 Mongoose 中推送 ObjectId

node.js - Express + PassportJS 无法读取闪信

node.js - 什么是对 Express 4 路由器上的某些路由进行身份验证的更好方法?

node.js - Node.js 中的安全性

javascript - 如何隐藏元素onclick jquery

javascript - 在 GraphQL 中搜索具有特定字符串的特定结果

javascript 媒体查询 - 加载 HTML 元素

javascript - 在 mousemove 上使用 JavaScript 应用转换不会即时更新

javascript - 如何实现请求认证?