如何使用Passport.js访问Cookie集 [英] How to access Cookie set with Passport.js
问题描述
我正在使用Passport.js来实现对我的Node-App的登录.但是在我的应用程序中,我需要访问用户的ID,目前,我不知道如何实现此目的!
I'm using Passport.js to achieve login to my Node-App. But in my app, I need to get access to the user's ID and currently, I don't have an idea how to achieve this thing!
我该如何访问用户ID或自己将其发送到Cookie中?
How can I access the user-id or should I send it in a cookie myself?
推荐答案
您应该在应用中的策略配置旁边引入以下代码:
You should introduce the following code in your app, next to the configuration of the strategies:
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
通过这种方式,当您通过身份验证的用户调用done
函数时,护照负责将userId存储在cookie中.
每当您要访问userId时,都可以在请求正文中找到它. (表示为req["user"]
).
In this way, when you invoke the done
function with the authenticated user, passport takes care of storing the userId in a cookie.
Whenever you want to access the userId you can find it in the request body. (in express req["user"]
).
如果要在会话中存储其他数据,还可以开发serializeUser
函数.我这样做:
You can also develop the serializeUser
function if you want to store other data in the session. I do it this way:
passport.serializeUser(function(user, done) {
done(null, {
id: user["id"],
userName: user["userName"],
email: user["email"]
});
});
您可以在此处找到更多信息: http://passportjs.org/docs/configure
You can find more here: http://passportjs.org/docs/configure
这篇关于如何使用Passport.js访问Cookie集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!