I have a question about the usage of sessions with express-session
. I really don't understand how the sessions are secure. For example in the following official guide: https://expressjs.com/en/resources/middleware/session.html they create a middleware to check if the user is authenticated:
// middleware to test if authenticated
function isAuthenticated (req, res, next) {
if (req.session.user) next()
else next('route')
}
But I don't understand, why isn't this middleware checking that the session is in fact, inside the DB? An attacker could just modify the session cookie with random values and there would be still some value in the user
field, even if it's a garbage value, no? So the function still would think this is an authenticated user.
Why is this not possible?
In my case, I am setting the userId
in the session and then every time someone makes a request, I retrieve its userId
, but I do not understand, what if someone modifies the cookie and gets a random userId
value? My application will think this user is authenticated, correct?
CodePudding user response:
why isn't this middleware checking that the session is in fact, inside the DB?
This check, which you rightly expect to be done, is already done before, in the express-session
middleware: This looks up the value of the session cookie in the session storage (which can be a database) and populates req.session
accordingly. Since the value of the session cookie is unguessable, an attacker who puts in a random value, will make req.session
undefined, and the isAuthentication
check will fail, as it should.