cookie-session: Correct logOut using Passport. ClearCookie doesn't delete cookies.
I’m using PassportJS and this code for logout:
.get("/logout", async (req, res) => {
await req.logout();
req.session = null;
await res.clearCookie(process.env.PROJECT_TITLE.toLowerCase());
await res.clearCookie(`${process.env.PROJECT_TITLE.toLowerCase()}.sig`);
return res.redirect("/");
});
It just changes the cookies but don’t delete them. Why?
It does delete them if I use just this code:
.get("/logout", async (req, res) => {
await res.clearCookie(process.env.PROJECT_TITLE.toLowerCase());
await res.clearCookie(`${process.env.PROJECT_TITLE.toLowerCase()}.sig`);
return res.redirect("/");
});
Where am I wrong?
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 40 (20 by maintainers)
This is an example remix that will do the
req.logout()and clear the cookie in your logout route: https://glitch.com/edit/#!/tiny-chinchillaHi @frederikhors
correct, that was the only change in my remix.
The issue I’m seeing is that
req.logoutis altering the session, which is why the session is getting updated in your logout request.I’m not very familiar with passport. Maybe can you explain exact what
req.logoutis doing apart from alteringreq.session? We may be able to determine this by understanding the specifics of whatreq.logoutdoes.But what I found is that the cookie is getting set on your logout because of the following:
(1) req.logout alters the
req.sessionobject, so a need to set the cookie is noted by this module (2) the code calls clearcookie, which has nothing to do with this module and this module has no idea your code did that. clearing a cookie is just setting a cookie with an expiration date in the past (3) the response ends and this module sees that (a) thereq.sessionobject was changed, thus it knows it needs to set the new value and (b)req.session.save()hasn’t been called, so it will automatically save the changes for youSo it seems like you have one of two options:
(a) don’t touch the
req.sessionif you don’t want a new value to be saved in the cookie (this is why I commented outreq.logout()OR
(b) call
req.session.save()to explicitly save the changes to the session thatreq.logout()made and then do the clear cookie calls.I hope that helps 👍
I haven’t forgotten. I don’t look through evey repo every day to determine what I need to do. I have a todo list. I can reopen this if it will make you happy but won’t make any difference for when I can get to it.
You cannot use both
req.session = nullto clear the session andres.clearCookie, as they end up conflicting (this module will override your clear commands because it think you want thereq.session = nullbehavior. If you want the cookies completely gone on log out, rather than just being set to an empty session, your the following: