15

我正在使用 Passport.js 来实现登录到我的 Node-App。但是在我的应用程序中,我需要访问用户的 ID,目前,我不知道如何实现这件事!

我如何访问用户 ID 或者我应该自己在 cookie 中发送它?

4

5 回答 5

25

您应该在您的应用程序中,在策略配置旁边引入以下代码:

passport.serializeUser(function(user, done) {
   done(null, user.id);
});

passport.deserializeUser(function(obj, done) {
   done(null, obj);
});

这样,当您done使用经过身份验证的用户调用该函数时,passport 会负责将 userId 存储在 cookie 中。每当您想访问 userId 时,您都可以在请求正文中找到它。(快递 req["user"])。

serializeUser如果您想在会话中存储其他数据,您也可以开发该功能。我这样做:

passport.serializeUser(function(user, done) {
   done(null, {
      id: user["id"],
      userName: user["userName"],
      email: user["email"]
   });
});

你可以在这里找到更多:http: //passportjs.org/docs/configure

于 2012-09-04T08:10:07.843 回答
19

添加到登录路径

res.cookie('userid', user.id, { maxAge: 2592000000 });  // Expires in one month

添加到注销路径

res.clearCookie('userid');
于 2013-03-14T11:51:28.587 回答
2

user1071182的回答是正确的,但没有明确将 cookie 设置代码放在哪里。

这是一个更完整的例子:

app.get("/auth/google/callback",
    passport.authenticate("google"),
    setUserIDResponseCookie,
    (req, res, next)=>{
        // if success
        if (req.user) {
            res.redirect("http://localhost:3000");
        } else {
            res.redirect("http://localhost:3000/login-failed");
        }
        next();
    });

function setUserIDResponseCookie(req, res, next) {
    // if user-id cookie is out of date, update it
    if (req.user?.id != req.cookies["myapp-userid"]) {
        // if user successfully signed in, store user-id in cookie
        if (req.user) {
            res.cookie("myapp-userid", req.user.id, {
                // expire in year 9999 (from: https://stackoverflow.com/a/28289961)
                expires: new Date(253402300000000),
                httpOnly: false, // allows JS code to access it
            });
        } else {
            res.clearCookie("myapp-userid");
        }
    }
    next();
}

注意:确保:

  1. 将显示的处理程序添加到authXXX/callback路由,而不是authXXX路由。
  2. passport.authenticate“明明白白”,即。没有重定向选项。如果您在那里设置重定向选项,cookie 将无法正确设置(据我所知)。相反,在设置 cookie 后添加自定义重定向代码。(如上图)
  3. 如果您有“退出”路由,请将上面的处理程序也添加到该路由。
于 2021-07-17T14:49:25.153 回答
0

如果您正在使用angular-fullstack生成器,这就是我修改setUserCookie以获取_id用户 cookie 的方式(稍后我可以在 AngularJS 中检索它)。

setUserCookie: function(req, res, next) {
    if (req.user) {
        req.user.userInfo['_id'] = req.user._id;
        console.log('Cookie', req.user.userInfo);
        // Splice in _id in cookie
        var userObjWithID = {
            "provider": req.user.userInfo.provider,
            "role": req.user.userInfo.role,
            "name": req.user.userInfo.name,
            "_id": req.user._id
        };
        res.cookie('user', JSON.stringify(userObjWithID));
    }
    next();
}
于 2014-02-13T09:11:17.017 回答
-1

或者,您可以执行以下操作:

passport.serializeUser(User.serializeUser());

passport.deserializeUser(User.deserializeUser());
 app.use((req, res, next) => {
  res.locals.login = req.isAuthenticated();
  res.locals.thisUser = req.user;
  next();
});
于 2017-08-16T05:18:48.327 回答