forwardemail / forwardemail/supertest

Cookies not provided properly with Express 'cookieSession' while testing the app with Supertest

Open
#479 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
14.4k
Forks
782
PR merge metrics
No merged PRs in 30d

Description

Hey!

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 that passport is deserializing/serializing user properly.

Versions:
- Express: 4.16.2
- PassportJS: 0.3.2
- Supertest: 2.0.1
- Superagent: 2.3.0

1. 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);
```

2. I run login before the tests (using async/await feature):
```
await request.post('/login').send({
email: 'some@email.com',
password: 'plainpassword'
});
```

3. 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 can not find the user ID in the cookie.

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.

Can you treat this as a bug or am I missing something?

Thanks!

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.