passport icon indicating copy to clipboard operation
passport copied to clipboard

req.logout not working with "local strategy"

Open pensierinmusica opened this issue 10 years ago • 51 comments

The req.logout method doesn't seem to delete the session values when invoked.

I'm using passport-local and cookie-session, with Express.

It looks like similar issues are discussed on StackOverflow.

Any ideas what might be causing the problem?

pensierinmusica avatar May 18 '14 22:05 pensierinmusica

Same thing here. Using passport-http, basic session, with restify.

I've tried both:

req.logout();
res.send( { message: 'Successfully logged out' } );

and:

req.session.destroy( function ( err ) {
    res.send( { message: 'Successfully logged out' } );
});

Neither of them are working. Any suggestions?

tybenz avatar May 29 '14 04:05 tybenz

Got the same problem. Seems to be due to changes in Express 4.0.

mathiasm74 avatar Jun 03 '14 15:06 mathiasm74

Same issue here, also using Express 4 + cookie-session.

phof avatar Aug 21 '14 23:08 phof

This is still a problem it would seem... anyone have a good solution yet?

iamsenseiken avatar Sep 02 '14 11:09 iamsenseiken

Same issue here

johnmastri avatar Oct 15 '14 02:10 johnmastri

I'm in the same boat. Any update?

chriskrycho avatar Nov 18 '14 19:11 chriskrycho

Same issue here. Express 4 + Passport

It seems only happening in Chrome (Version 38.0.2125.122.) Is that possible ?

itsmichaeldiego avatar Nov 27 '14 19:11 itsmichaeldiego

Follow-up: for me, it appears to have been a dependency issue (possibly deriving from an automated refactoring that didn't correctly exclude node_modules). I nuked my local node_modules directory, ran npm install, and got a working session logout.

Note that for my tests with jasmine-node and request to work correctly, I had to make sure to supply a request.jar() instance in the jar field of the request object.

Here's my logout:

// Express middleware function for logging out a user. The action is successful
// if the user is no longer authenticated.
var logout = function (req, res, next) {
  // Get rid of the session token. Then call `logout`; it does no harm.
  req.logout();
  req.session.destroy(function (err) {
    if (err) { return next(err); }
    // The response should indicate that the user is no longer authenticated.
    return res.send({ authenticated: req.isAuthenticated() });
  });
};

This works fine with [email protected], [email protected], [email protected], [email protected]. I'm using the connect-pg-simple session store middleware with it, with no issues.

chriskrycho avatar Dec 01 '14 14:12 chriskrycho

same here, I'm using "express": "^4.13.3","express-session": "^1.12.1", "passport": "^0.3.2","passport-local": "^1.0.0", "sequelize": "^3.14.1".

when logouts it shows req.user = null, but after page refresh it comes again, I think problem is in

passport.deserializeUser(function (id, done) { User.findById(id).then(function (user) { var usr = user.get({ plain: true }); done(null, usr); }) });

any help??

akashdeepshah avatar Nov 26 '15 05:11 akashdeepshah

Same issue here. Any update ? @akashdeepshah you have found the solution with function passport.deserializeUser ?

webus avatar Jan 26 '16 12:01 webus

@webus , Previously I was using angular service to logout and it failed, and then I tried directly and it worked !!! hope in your case it works too..

akashdeepshah avatar Jan 27 '16 04:01 akashdeepshah

Same issue here. Express 4 + Passport

How can I fix this? Should I downgrade Express from 4 to 3 ?!

omidgolparvar avatar Apr 08 '16 20:04 omidgolparvar

Dears @akashdeepshah @webus @pensierinmusica @tybenz @mathiasm74 @phof @samuraiken @johnmastri @chriskrycho @MichhDiego It think I found a solution. Please check it out and share your results. I use Express v4.13.4 and Passport v0.3.2 in my project. When I want to checkout logged in user, I use req.isAuthenticated() and store it's returned value in a variable. for example:

var _LoggedIn = (req.isAuthenticated() ? true : false);

so, I don't use req.user anymore, and it works for me, and I hope it works for all of us. finally, if I did anything wrong, tell me please. thanks. :)

omidgolparvar avatar Apr 09 '16 02:04 omidgolparvar

@omidgolparvar I am really thankful for your answer, but that project is dead! Haha, thanks again anyways.

itsmichaeldiego avatar Apr 12 '16 01:04 itsmichaeldiego

Any update on this? Still having this issue. I am using req.logOut() and req.session.destroy(). When I do, the session seems to be destroyed, but when I refresh it still has the old request Authentication and user.

I am using req.isAuthenticated() and it is still getting back a "true" after refresh.

Any recommendations?

assadtony avatar Jun 03 '16 13:06 assadtony

@assadtony Did you check https://github.com/jaredhanson/passport/issues/246#issuecomment-207683415 ?

itsmichaeldiego avatar Jun 03 '16 13:06 itsmichaeldiego

Yeah, just figured it out, some other post helped me out with this solution, and it worked for me in conjunction with the comment mentioned. Thanks @MichhDiego ;)

app.use(session({ ... resave: false, .... }));

assadtony avatar Jun 03 '16 14:06 assadtony

@omidgolparvar can you explain how that helps you logout from the session for user?

peacemakr avatar Dec 07 '16 23:12 peacemakr

@assadtony You referred to some other post helping you find the solution to this. Can you remember what that was? I'm having the same issue, it looks like the session is being destroyed but when I return to the login page the user is still authenticated.

Ryca77 avatar Mar 19 '17 19:03 Ryca77

this may help, http://stackoverflow.com/a/43429283/2077479

sattha avatar Apr 15 '17 17:04 sattha

I had the same problem too, but the following workaround solved it: // Express Session app.use(session({ secret: 'secret', saveUninitialized: false, resave: false, cookie: { maxAge: 1000 } })); Then on the logout route router.get('/logout', function (req, res) { req.logOut(); // remove all session data req.session = null; res.redirect('/login'); });

Cheers.

Harrisonkamau avatar Jun 09 '17 12:06 Harrisonkamau

I have the same problem. session null or destroy solutions seems a bit ham fisted. If you just want to log out and keep other session variables, this doesn't work. Why doesn't req.logout() simply work? Seems like a bug to me. If there is a reason why logout couldn't work, it at least should throw a warning. The underlying problems seems to be that the relevant session variables aren't actually cleared.

mschipperheyn avatar Sep 15 '17 12:09 mschipperheyn

So I am having these issues using Express 4.15.4, passport 0.4.0, passport-oauth2 1.4.0, cookie-session 1.3.1. Symptoms are the same as described above. I have:

app.get('/logout', (req, res) => {
  req.logout();
  res.redirect('/');
});

My / path is protected - if the user is not logged in, it will redirect to login. I added this line to my middleware router: console.log(req.path, ':', req.isAuthenticated()); In Chrome, I navigated to /, confirmed I was still logged in, then navigated to /logout. I ended up back at / logged in. But interestingly, this is how I got there:

/ : true
/logout : true
/ : false
/login : false
/login/callback : false
/ : true

So it looks like (at least in my case), it is logging me out, but when forwarded to passport.authenticate('oauth2'), I'm automatically logged back in without prompt. Any thoughts? Is this symptom the same for everyone else here?

kathleentully avatar Sep 20 '17 20:09 kathleentully

Just logged a similar issue on express

mschipperheyn avatar Sep 20 '17 20:09 mschipperheyn

@kathleentully Try creating an express session and use it to destroy the current_user: const expressSession = require('cookie-session');

// you can set the expiry date let expiryDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // 7 days

const session = expressSession( { secret: 'very_secret', saveUninitialized: true, resave: false, cookie: { secureProxy: true, httpOnly: true, expires: expiryDate } });

app.use(session);

// Log out the user app.get('/logout', (req, res) => { req.logout(); req.session.destroy(); res.redirect('/'); })

Hope this works :)

ghost avatar Sep 21 '17 16:09 ghost

I am having trouble getting my system to log out with PassportJS. It seems the logout route is being called, but its not removing the session. I want it to return 401

aayush1408 avatar Nov 02 '17 03:11 aayush1408

This is still a problem it would seem... anyone have a solution yet?

ghost avatar Dec 11 '17 15:12 ghost

Having the same problem here

kievo23 avatar Dec 13 '17 14:12 kievo23

@kievo23 Would you mind sharing a gist of the failing code?

ghost avatar Dec 13 '17 15:12 ghost

I had same issue so i just looked over the source code of the passport library. In passport/lib/sessionmanager.js , I found this code

SessionManager.prototype.logOut = function(req, cb) {
  if (req._passport && req._passport.session) {
    delete req._passport.session.user;
  } 
  cb && cb();
}

so i changed this code like this

SessionManager.prototype.logOut = function(req, cb) {
  if(req._passport){
    console.log(req._passport);
  }
   if (req._passport && req._passport.session) {
    delete req._passport.session.user;
  } else {
    delete req.session.passport;
  }
  cb && cb();
}

and below is what my console shows

{ instance: 
   Authenticator {
     _key: 'passport',
     _strategies: { session: [Object], local: [Object], facebook: [Object] },
     _serializers: [ [Function] ],
     _deserializers: [ [Function] ],
     _infoTransformers: [],
     _framework: 
      { initialize: [Function: initialize],
        authenticate: [Function: authenticate] },
     _userProperty: 'user',
     _sm: SessionManager { _key: 'passport', _serializeUser: [Function: bound ] },
     Authenticator: [Function: Authenticator],
     Passport: [Function: Authenticator],
     Strategy: { [Function: Strategy] Strategy: [Circular] },
     strategies: { SessionStrategy: [Object] } } }

I think it is because we have req._passport but req._passport.session. Although My version of logOut is working, library seems to be updated.

boomkim avatar Jan 08 '18 08:01 boomkim