Lusca csrf not working as expected - http request using old token

Viewed 448

I was trying to set up CSRF protection with lusca on my Express.js application. Not it looks like this:

this.app.use(lusca({
      csrf: {
        cookie: {name: '_csrf'}
      },
      hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
      nosniff: true,
      referrerPolicy: "same-origin",
      xframe: "SAMEORIGIN",
      xssProtection: true,
    }));

And on client side as follow:

const res = await axios.post(`${Constants.apiUrl()}/${Constants.paths.login}`, 
                credentials, {
                    withCredentials: true,
                    xsrfCookieName: '_csrf'
                });

On the server-side, I also set some headers to be able to send cookies with request - res.header('Access-Control-Allow-Credentials', 'true').

Probably I'm missing some important part of how CSRF protection works. Now each time with the response, I'm getting new csrf token but this means that my new HTTP POST request sending the previous token that already outdated. What I'm missing?

1 Answers

Finally, I found the problem after testing for 3 hours. You need to add the secret of the csrf. Also, if you are using Angular, you need to add angular: true into the csrf.

this.app.use(lusca({
    csrf: {
        cookie: {name: '_csrf'},
        secret: 'qwerty'
    },
    hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
    nosniff: true,
    referrerPolicy: "same-origin",
    xframe: "SAMEORIGIN",
    xssProtection: true,
}));
Related