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!
How can I access the user-id or should I send it in a cookie myself?
In this route, passport. authenticate() is middleware which will authenticate the request. By default, when authentication succeeds, the req. user property is set to the authenticated user, a login session is established, and the next function in the stack is called.
Authorization is performed by calling passport. authorize() . If authorization is granted, the result provided by the strategy's verify callback will be assigned to req.account . The existing login session and req.
The local authentication strategy authenticates users using a username and password. The strategy requires a verify callback, which accepts these credentials and calls done providing a user. passport. use(new LocalStrategy( function(username, password, done) { User.
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);
});
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"]
).
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"]
});
});
You can find more here: http://passportjs.org/docs/configure
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With