0

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...

AndroC
  • 4,758
  • 2
  • 46
  • 69

1 Answers1

2

By default, the express-sesssion middleware will check for an existing session cookie and if one does not exist, it will create a new cookie and a new session object on any request that the middleware runs on.

To support a login feature, you have to actually implement some form of authentication and not create the new session cookie and session object if the login credentials themselves do not validate. Or, you can just have a flag in your session object that indicates whether the login for that session has been validated or not and you check both for the existence of a session and that the validated flag has been set.

The bits of code you show look like every incoming connection just creates a new session object (if one doesn't already exist) and all your validation code is doing is checking to see if a session object exists which it always will because as soon as you get rid of it, then next incoming request will run the middleware again and create a new session cookie and object.

See how to implement login auth in node.js for an example.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • `req.session.userId` checks whether userId is present. This will not be set automatically by middleware... I do have authentication but I skipped some parts. Thank you for response. There wasn't any problem as it turns out... (I edited the question) – AndroC Apr 30 '18 at 16:45