I initialize express-session:
const session = require('express-session')
const MongoStore = require('connect-mongo')(session);
//use sessions for tracking logins
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: false,
store: new MongoStore({
mongooseConnection: mongoose.connection
})
}));
My middleware for checking authentication:
function requiresLogin(req, res, next) {
if (req.session && req.session.userId) {
console.log('Session OK ' + JSON.stringify(req.session) );
return next();
} else {
var err = new Error('You must be logged in to view this page.');
err.status = 401;
return next(err);
}
}
My logout endpoint:
// GET /logout
exports.logout = function(req, res, next) {
if (req.session) {
// delete session object
req.session.destroy(function(err) {
if(err) {
return next(err);
} else {
req.session = null;
console.log("logout successful");
return res.redirect('/');
}
});
}
};
My tests:
I submit a request to my test endpoint that is behind the requiresLogin middleware and I get (as expected):
Error: You must be logged in to view this page.
I submit request to my login endpoint and I get a cookie:
set-cookie: connect.sid=s%3A0doMoVwGPkcVUgar3uP5WR36b7k9_v27.O2B8vl35TQLiet3WltP2UAH3iuaeif3%2BPDActkTBYUw; Path=/; HttpOnly
I use this cookie again on my test endpoint:
Session OK {"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"userId":"5ae6ddee1239c157ec36c06c"}
I perform /logout, for which I get
logout successful
After that I try my test endpoint again with the cookie that I believe I just destroyed:
Session OK {"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"userId":"5ae6ddee1239c157ec36c06c"}
The session is untouched in the database after the successful destroy.
Why can I use my session authentication cookie after I destroyed the session?
EDIT
Question should be deleted. I was using the wrong Cookie when I was performing /logout. Stupid mistake, my bad...