[Vuejs]-Express & Csurf rejects Vue (Axios) post request

0๐Ÿ‘

โœ…

So I realized that csurf looks for two things . A cookie (this is not very apparent from the error but nevertheless) and the token to be sent via header . Axios by default apparently does not support cookies so I decided to move to a JWT header approach.

0๐Ÿ‘

Your way of sending the token via router.get('/getCSRF/', ...) does not seem very secure to me, as any attacker could also easily get this token via this get request.

If you use app.use(csurf({ cookie:true })), then Express will validate every POST/PUT/DELETE request based on a cookie, but you need to set this cookie yourself.
(Csurf sets a cookie named _csrf but this is not the actual CSRF token)

I got it working this way:
Nodejs:

app.use(cookieParser());
app.use(
    csrf({
        // compare the XSRF-TOKEN cookie with the X-XSRF-TOKEN header on every post request
        cookie: {
            secure: true,
            sameSite: 'strict',
        },
    })
);

app.use(function (req, res, next) {
    // set the XSRF-TOKEN cookie so the client can send it back in the X-XSRF-TOKEN header
    res.cookie('XSRF-TOKEN', req.csrfToken());
    next();
});

I used Nuxt as my client. Nuxt.config.js:

modules: [
    '@nuxtjs/axios',
],

axios: {
    credentials: true, // this will take the XSRF-TOKEN from the cookie and set it in the X-XSRF-TOKEN header
    baseURL: nuxtBaseUrl,
    browserBaseURL: nuxtBrowserBaseUrl,
},

publicRuntimeConfig: {
    axios: {
      credentials: true, // this will take the XSRF-TOKEN from the cookie and set it in the X-XSRF-TOKEN header
      baseURL: nuxtBaseUrl,
      browserBaseURL: nuxtBrowserBaseUrl,
    },
},

Alternative without nuxt:

const instance = axios.create({
  baseURL: 'https://my-server/',
  withCredentials: true, // this will take the XSRF-TOKEN from the cookie and set it in the X-XSRF-TOKEN header
});

instance.post('http://my-server/api/users/checkEmail', {
    email: this.user.Email
}

Leave a comment