Sovos
Sovos

Reputation: 3390

express.js understanding sessions security

I cannot understand some points about how express.js sessions work

when I do something like

server.use express.cookieParser()
server.use express.cookieSession { secret: 'whatever' }

and then setup the login sequence like

server.post '/login', (req, res)->

  # checks that provided psw and username exist in db

  req.session.user =
    id: dbID
    username: postedUsername
    psw: postedPsw

  res.redirect '/'

is req.session.user safe with all parameters not encrypted?

and should I check if username and psw are correct at each point like so:

server.use (req, res, next) ->

  # checks that provided psw and username exist in db
  # otherwise destroy session

?

many thanks for your time

Upvotes: 0

Views: 369

Answers (1)

Hector Correa
Hector Correa

Reputation: 26690

is req.session.user safe with all parameters not encrypted?

When you use { secret: 'whatever' } you are just hashing the cookie as it is stored in the user's browser. This is better than saving a value in plain text but it is not extremely secure (which is usually OK because you shouldn't be storing sensitive information in cookies anyway)

The values are transferred from the browser to your app in plain text as you've noticed.

If you need them to be secure your best bet is to use HTTPS and a certificate. Don't roll your own "encryption", instead use a proven protocols (like HTTPS/SSL)

and should I check if username and psw are correct at each point like so:

Typically you only ask for username/password once (in the login process), check for them in the database once (again, during the login process), and issue a "session token" that you use afterwards to validate that the session is from a valid user. The session id is something that you can cookie since it usually last for only a few minutes (depending how long you want to cookie the value)

The process to validate the session might need to be performed on each hit to the server, just as you were thinking for the username/password. Some people store session IDs in a cache database (or an in-memory database) so that this process is extremely fast and you don't slow down users.

You can create an "authenticate middleware" in Express:

var authenticate = function(req, res, next) {

  if(req.cookies.sessionToken) {
    // call some method to validate the session)
    validateSession(req, res, next);
  }
  else {
    // Not authenticated (up to you what to do) 
    next();
  }

}

...and then share this middleware across your routes:

app.get('/somethingA', authenticate, somethingA);
app.get('/somethingB', authenticate, somethingB);

Upvotes: 2

Related Questions