krakenjs / lusca

Application security for express apps.
Other
1.78k stars 123 forks source link

Error: CSRF token mismatch #97

Closed erbridge closed 7 years ago

erbridge commented 7 years ago

I'm having trouble getting CSRF working with HTTPS on AWS. I have it working fine locally, using a self-signed SSL certificate, but on the staging server behind a load balancer, I get Error: CSRF token mismatch. I am using Express, and Lusca is set up as below. _csrf is being sent in the POST body.

app.use(/^(?!.*\/res\/.*\/upload).*$/, lusca({
  csrf:   true,
  xframe: 'DENY',
  hsts:   {
    maxAge:            31536000,
    includeSubDomains: true,
    preload:           true,
  },
  xssProtection: true,
}));

Any idea what's going wrong?

shaunwarman commented 7 years ago

The secret is saved in the session. Any chance of a new session or sid is lost?

erbridge commented 7 years ago

That was indeed the issue. I had failed to set app.set('trust proxy', 1).

Thanks for the pointer.

tuturis commented 6 years ago

I have similar problem. Over 60% of the time lusca CSRF works every time, but it's still annoying. Setup is express 4.*, nginx proxy, ssl.

app.enable('trust proxy', 1)
app.set('trust proxy', 'loopback, linklocal, uniquelocal')
app.use(flash());
app.use(session({
    key: 'sid', 
    resave: true,
    saveUninitialized: true,
    secret: process.env.SESSION_SECRET,
    cookie: { maxAge: 60000, secure: true},
      store: new MongoStore({
        url: process.env.MONGODB_URI || process.env.MONGOLAB_URI,
        autoReconnect: true,
        clear_interval: 3600
    })  
}));
app.use(lusca.csrf({ secret: 'qwerty' }));
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));
app.use(lusca.hsts({
    maxAge:            31536000,
    includeSubDomains: true,
    preload:           true,
  }));

What could be the case?