Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express Passport.js: req.user VERSUS req.session.passport.user

As per this article

http://toon.io/understanding-passportjs-authentication-flow/

it looks as though PassportJS/Express store the logged in user in two places

req.user

and

req.session.passport.user

why both? which one should I use? When I logout with passport, does it destroy both req.user and req.session.passport.user?

like image 901
Alexander Mills Avatar asked Nov 21 '14 06:11

Alexander Mills


People also ask

Does passport use session?

Passport uses serializeUser function to persist user data (after successful authentication) into session. The function deserializeUser is used to retrieve user data from session and perform some condition-based operations. Now all the endpoints hitting the backend server will go through passport.

Does passport js use session?

Passport is carefully designed to isolate authentication state, referred to as a login session, from other state that may be stored in the session. Applications must initialize session support in order to make use of login sessions. In an Express app, session support is added by using express-session middleware.

What does req login do passport?

Passport exposes a login() function on req (also aliased as logIn() ) that can be used to establish a login session. req. login(user, function(err) { if (err) { return next(err); } return res.

What is passport Express js?

Passport is Express-compatible authentication middleware for Node. js. Passport's sole purpose is to authenticate requests, which it does through an extensible set of plugins known as strategies.


1 Answers

You should always, always use req.user in your own code -- this is important because if you use req.session.passport.user, you're essentially pulling user information out of a session cookie (which may be outdated).

It's always best to rely on req.user as opposed to cookie data directly, as depending on your implementation, that information might be out of date.

And to answer your question: if you log a user out, both req.session and req.user will no longer be available.

like image 164
rdegges Avatar answered Sep 21 '22 04:09

rdegges