'Request cookie not returning Express session data as expected

I am trying to build a rudimentary login feature and test that it creates a session I can use later on. I am using express-session and redis to persist the session data. Here is my setup:

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(express.static(path.join(__dirname, 'client/build')))

app.use(cookieParser(process.env.COOKIE_SECRET))
app.use(session({
  store: new redisStore({
    host: '127.0.0.1',
    port: 6379
  }),
  secret: process.env.SESSION_SECRET,
  cookie: {maxAge: 1800},
  name: 'appName',
  resave: false,
  saveUninitialized: false
}))

app.use('/', routes)

Then my login route:

router.post('/api/login', (req, res) => {
  req.session.userId = req.body.id
  req.session.email = req.body.email

  //do I need to send out a cookie with the session created here?
  res.set({'Set-Cookie': 'appSession=' + req.session.id})
  res.status(200).send({
    "message": `User ${req.body.id} logged in with cookie ${req.session.id}`
  })
})

Then it is my understanding I should be able to read and add to this session for any requests where I send the cookie back. Here is my API to test that:

router.post('/api/test' (req, res) => {
  if(req.session && req.session.userId) {
    res.status(200).send({"message": `User ID ${req.session.userId} is  authenticated`})
     } else {
       res.status(401).send({"message": `User ID ${req.session.id} is not authenticated`})
   }
})

I am sending a request to this API using Postman with header Cookie: appName=${sessionID} using the sessionID created in the api/login route. This always creates a new sessionId and returns the 401.

Is my understanding correct? If so, how do I create this expected behaviour?



Solution 1:[1]

I've now got an answer for this - there were a couple of bits that I didn't think were clear from other sources on the internet.

Firstly, it's useful to debug the problem if you're having trouble with express-session, by running your server with DEBUG=express-session node server.js

When I did this I realised express-session wasn't finding the created session. This was because I was setting the maxAge property in seconds and not milliseconds, so it was expiring immediately. Idiot.

There was then a further problem. I got the following debug output when trying to retrive the session:

  express-session cookie unsigned +1ms
  express-session no SID sent, generating session +1ms

This was the cookie parser not finding my SessionId, because the cookie parser needs to use the same key as express-session. Again, pretty obvious in retrospect.

Hopefully this helps someone that gets the same errors.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MDalt