0

This is driving me nuts. I have tried reading the lusca source code but found it hard to understand.

Checked several examples too, but since each config is different, and the only debugging output I have are two strings to compare, I'd better ask for some help!

Here's the code server side:

app.use([
cookieParser(process.env.SESSION_SECRET),
session({
  resave: false,
  saveUninitialized: true,
  secret: process.env.SESSION_SECRET,
  store: new MongoStore({ url: MONGO_URL, autoReconnect: true }),
  cookie: {
    secure: process.env.NODE_ENV === 'production'
  },
}), lusca({
  csrf: true,
  xframe: 'SAMEORIGIN',
  xssProtection: true,
})]);

And from the clientside, I send Ajax POST requests with the x-csrf-token:l0gH3xmssge53E/p2NsJ4dGnHaSLdPeZ+bEWs= header in it:

fetch(url, {
  method: 'POST',
  credentials: 'include',
  headers: {
    'x-csrf-token': CSRF_TOKEN
  }
});

Crazy thing is, it's working locally, but as soon as I go https in production, I get the 403 Forbidden error message.

Here are the versions I use:

"cookie-parser": "1.4.3",
"express-session": "1.15.3",
"lusca": "1.5.1",

Also I read this from the express/session doc:

Note Since version 1.5.0, the cookie-parser middleware no longer needs to be used for this module to work.

But as far as I'm concerned, I need to store some persistent ID of the users (longer than the session). I need to use cookies for that, right?

I'd like to understand better on the whole session/cookie thing, but until now I never found any useful resource on the topic.

Thanks!

Augustin Riedinger
  • 20,909
  • 29
  • 133
  • 206

1 Answers1

0

If you are running your Node.js server behind a proxy you will need to set trust proxy to true:

var isProductionEnv = process.env.NODE_ENV === 'production';

app.use([
cookieParser(process.env.SESSION_SECRET),
session({
  resave: false,
  saveUninitialized: true,
  secret: process.env.SESSION_SECRET,
  store: new MongoStore({ url: MONGO_URL, autoReconnect: true }),
  proxy: isProductionEnv,
  cookie: {
    secure:isPrudictionEnv,
  },
}), lusca({
  csrf: true,
  xframe: 'SAMEORIGIN',
  xssProtection: true,
})]);


app.set('trust proxy', isProductionEnv);

Check out this stack overflow answer. Also check out this page on Express behind proxies.

mkhanoyan
  • 1,958
  • 18
  • 15
  • My app is hosted in docker and a nginx does some routing first, is that what should be called a proxy? Anyway, I tried the `trust proxy` thing and it doesn't work. :( Thanks for the help! – Augustin Riedinger Oct 06 '17 at 13:10
  • It looks like you might need to add a `proxy` setting to the session middleware options as well. I will edit the answer so you can take a look. – mkhanoyan Oct 08 '17 at 04:07
  • Still no luck. But I'm not sure this is it: Nginx doesn't do HTTP proxying and docker shouldn't be an issue here. My feeling is that this has to do with the cookie being secure+used in a session ... – Augustin Riedinger Oct 09 '17 at 10:26