Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Cookie set with Passport.js

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?

like image 890
Lukas Olsen Avatar asked Sep 04 '12 07:09

Lukas Olsen


People also ask

What does passport authenticate () do?

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.

How does Passport JS handle authorization?

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.

What is passport LocalStrategy?

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.


1 Answers

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

like image 189
AnduA Avatar answered Oct 13 '22 20:10

AnduA