Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport.js: how to access user object after authentication?

I'm using Passport.js to login a user with username and password. I'm essentially using the sample code from the Passport site. Here are the relevant parts (I think) of my code:

app.use(passport.initialize()); app.use(passport.session());  passport.serializeUser(function(user, done) {     done(null, user); });  passport.deserializeUser(function(obj, done) {     done(null, obj); });  passport.use(new LocalStrategy(function(username, password, done) {     User.findOne({ username: username }, function(err, user) {         if (err) {             return done(err);         }         if (!user) {             return done(null, false, { message: 'Incorrect username.' });         }         if (!user.validPassword(password)) {             return done(null, false, { message: 'Incorrect password.' });         }         return done(null, user);         });     } ));  app.post('/login',     passport.authenticate('local', { failureRedirect: '/login/fail', failureFlash: false }),     function(req, res) {         // Successful login         //console.log("Login successful.");         // I CAN ACCESS req.user here }); 

This seems to login correctly. However, I would like to be able to access the login user's information in other parts of the code, such as:

app.get('/test', function(req, res){     // How can I get the user's login info here?     console.log(req.user);  // <------ this outputs undefined }); 

I have checked other questions on SO, but I'm not sure what I'm doing wrong here. Thank you!

like image 315
kurisukun Avatar asked Feb 19 '13 07:02

kurisukun


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.

Does Passport js use OAuth?

Thankfully, Passport shields an application from the complexities of dealing with OAuth variants. In many cases, a provider-specific strategy can be used instead of the generic OAuth strategies described below. This cuts down on the necessary configuration, and accommodates any provider-specific quirks.

Where is the user object located in a passport?

In reference to the Passport documentation, the user object is contained in req.user. See below. app.post ('/login', passport.authenticate ('local'),function (req, res) { // If this function gets called, authentication was successful. // `req.user` contains the authenticated user. res.redirect ('/users/' + req.user.username); });

How do I authenticate a user using passport?

To authenticate, Passport first looks at the user's login details, then invokes a verified callback ( done ). If the user gets properly authenticated, pass the user into the callback. If the user does not get appropriately authenticated, pass false into the callback.

How to use NodeJS passport to authenticate a user?

Now that Nodejs passport has got all it needs to authenticate the user, let's run the authenticateUser () function in the app.js and make Nodejs passport effective in the entire application. Finally, let us connect everything we have configured to app.js.

What is user serialization in passport JS?

For the client to cache the information, passport.js serializes the user. The most straightforward implication of user serialization is, "Hey passport, grab the authenticated user's id and store in the session in the database." When the session expires, passport.js deserializes the user.


Video Answer


2 Answers

Late to the party but found this unanswered after googling the answer myself.

Inside the request will be a req.user object that you can work withr.

Routes like so:

app.get('/api/portfolio', passport.authenticate('jwt', { session: false }), stocks.buy); 

Controller like this:

buy: function(req, res) {       console.log(req.body);       //res.json({lel: req.user._id});       res.json({lel: req.user});     } 
like image 120
Darcys22 Avatar answered Sep 28 '22 00:09

Darcys22


In reference to the Passport documentation, the user object is contained in req.user. See below.

    app.post('/login',       passport.authenticate('local'),function(req, res) {        // If this function gets called, authentication was successful.        // `req.user` contains the authenticated user.        res.redirect('/users/' + req.user.username);      }); 

That way, you can access your user object from the page you redirect to.

In case you get stuck, you can refer to my Github project where I implemented it clearly.

like image 33
L.T Avatar answered Sep 28 '22 02:09

L.T