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, if th
I was having the same issue, and it turned out to not be a problem with Passport functions at all, but rather in the way I was calling my /logout
route. I used fetch to call the route:
(Bad)
fetch('/auth/logout')
.then([other stuff]);
Turns out doing that doesn't send cookies so the session isn't continued and I guess the res.logout()
gets applied to a different session? At any rate, doing the following fixes it right up:
(Good)
fetch('/auth/logout', { credentials: 'same-origin' })
.then([other stuff]);
I don't know how but ng-href="/signout"
solved my problem. Previously I have used service to logout, but instead I've used it directly.
I was having the same issue. Turned out that my version of passport wasn't compatible with Express 4.0. Just need to install an older version.
npm install --save express@3.0.0
Brice’s answer is great, but I still noticed an important distinction to make; the Passport guide suggests using .logout()
(also aliased as .logOut()
) as such:
app.get('/logout', function(req, res){
req.logout();
res.redirect('/'); //Can fire before session is destroyed?
});
But as mentioned above, this is unreliable. I found it behaved as expected when implementing Brice’s suggestion like this:
app.get('/logout', function (req, res){
req.session.destroy(function (err) {
res.redirect('/'); //Inside a callback… bulletproof!
});
});
Hope this helps!
Destroying session by yourself looks weird. I faced with this issue having next configuration:
"express": "^4.12.3",
"passport": "^0.2.1",
"passport-local": "^1.0.0",
I should say that this configuration works well.
The reason of my issue was in custom sessionStore
that I defined here:
app.use(expressSession({
...
store: dbSessionStore,
...
}));
To be sure that your issue here too just comment store line and run without session persisting. If it will work you should dig into your custom session store. In my case set
method was defined wrong. When you use req.logout()
session store destroy()
method not invoked as I thought before. Instead invoked set
method with updated session.
Good luck, I hope this answer will help you.
simply adding req.logOut(); solved this issue ; "O" should be capitalized