Passport.js を使用して Node-App にログインしています。しかし、私のアプリでは、ユーザーの ID にアクセスする必要があり、現在、これを実現する方法がわかりません!
ユーザー ID にアクセスするにはどうすればよいですか、それとも自分で Cookie で送信する必要がありますか?
Passport.js を使用して Node-App にログインしています。しかし、私のアプリでは、ユーザーの ID にアクセスする必要があり、現在、これを実現する方法がわかりません!
ユーザー ID にアクセスするにはどうすればよいですか、それとも自分で Cookie で送信する必要がありますか?
ストラテジーの構成の横に、アプリに次のコードを導入する必要があります。
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"]
});
});
ログインパスに追加
res.cookie('userid', user.id, { maxAge: 2592000000 }); // Expires in one month
サインアウト パスに追加
res.clearCookie('userid');
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();
}
注: 次のことを確認してください。
authXXX/callback
ルートではなくルートに追加しauthXXX
ます。passport.authenticate
「明白に」呼び出します。リダイレクトオプションなし。そこにリダイレクト オプションを設定すると、Cookie が正しく設定されません (私の記憶によると)。代わりに、Cookie が設定された後にカスタム リダイレクト コードを追加します。(上記のように)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();
}