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ジェネレーターを使用している場合、これはユーザー CookiesetUserCookieを取得するように変更した方法です_id(後で 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 に答える