5

I have an issue testing the Express app with Supertest, using the 'cookieSession' from Express. Everything works fine, when I use session from Express, but cookieSession just doesn't work with PassportJS properly.

I am using PassportJS to authenticate the user and set the user to request object (req.user). So the /login works as expected, it returns the right set-cookie header, but on the next request, the authentication fails, which doesn't set the req.user property with the user object, even though it is deserializing/serializing user properly

Environment

Versions:

  • Express: 4.16.2
  • PassportJS: 0.3.2
  • Supertest: 2.0.1
  • Superagent: 2.3.0

This is how I initialize the superagent:

import * as supertest from 'supertest';
import * as superagent from 'superagent';
import app from '../../app';
const request = supertest.agent(app);

I run login before the tests (using async/await feature):

await request.post('/login').send({
  email: 'some@email.com',
  password: 'plainpassword'
});

Then I make first request to the backend for retrieving data:

const readResponse: superagent.Response = await             
request.post('/getData').send(requestBody);

And this is where it fails. It returns me the status code 401, beacuse PassportJS doesn't provide the user data to request object. Is it not in req.user perhaps?

In the app.ts I set the cookieSession and passportJS session like that:

app.use(cookieSession({
  keys: [process.env.SESSION_SECRET],
  maxAge: 24 * 60 * 60 * 1000 * 14 // 14 days
}));
app.use(passport.initialize());
app.use(passport.session());

BUT: If I use the normal session (which is storing data in the database):

app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: process.env.SESSION_SECRET,
  cookie : {
    expires: false
  },
  store: new MongoStore({
    url: process.env.MONGODB_URI || process.env.MONGOLAB_URI,
    autoReconnect: true
  })
}));
app.use(passport.initialize());
app.use(passport.session());

then everything works like a charm (except that I have some other issues, which was the reason why I switched to cookieSession.

Thanks!

spinner
  • 73
  • 7

0 Answers0