koa-passport logout() is not clearing session
Asked Answered
P

2

6

I am using koa, koa-passport and koa-session to log users in which works fine but when I call ctx.logout() the user can refresh and still be logged in. It seems that ctx.session and/or the cookies are not being correctly cleared.

This still fails when using Postman to make requests.

import Koa = require('koa');
import session = require('koa-session');
import passport = require('koa-passport');

....

app.keys = ['******'];
app.use(session({}, app));

....

app.use(passport.initialize());
app.use(passport.session());

....

router.get('/logout', (ctx: Context) => {
    if (ctx.isAuthenticated()) {
			ctx.logout();
			ctx.session = null; // Added this but still nothing
		}

		ctx.response.body = true;
});

I have found plenty of examples with Express including the following but not having any luck with Koa: https://github.com/expressjs/cookie-session/issues/104

Penitent answered 23/4, 2019 at 20:23 Comment(1)
I have the same problem... did you find a solution?Launder
D
2

I have take this answer from https://github.com/expressjs/cookie-session/issues/104 so you can find the full history of the dialog, but I just some save someone time and write the the answer below:

await ctx.logout();
ctx.session = null;

I guess he just didn't know, that ctx.logout is async function

Deputation answered 3/12, 2019 at 1:29 Comment(0)
L
0
res.logout()

Sets passport to {} in the session cookie, but leaves the cookie in place. For example:

{
  cookie: {
    originalMaxAge: 604800000,
    expires: '2022-01-17T19:14:31.872Z',
    secure: false,
    httpOnly: true,
    path: '/'
  },
  passport: {}
}

This would be helpful for storing anything else with the cookie.

To actually remove the cookie, use res.clearCookie() like this:

function deauthenticateSession(req: Request, res: Response, next: NextFunction) {
  // http://www.passportjs.org/docs/logout/ removes passport from the cookie, not the cookie from the browser
  // https://github.com/expressjs/cookie-session/issues/104#issuecomment-416249687
  res.clearCookie('connect.sid', { path: '/', httpOnly: true })
  res.status(200).json({})
}
Leibowitz answered 10/1, 2022 at 20:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.