0

I have an Express Server with an endpoint that generates the csrf token for the client,

Now, I tried sending back the token in my axios request as below but I keep getting the usual Forbidden: invalid csrf token error.

Below is my code:

static async attachCSRFTokenToHeaders(headers) {
    let csrfTokenRequest = await axios.get(EndPoints.CSRF_TOKEN);
    let csRefToken = csrfTokenRequest.data;
    headers['X-CSRF-TOKEN'] = csRefToken.csrfToken;
}

static async getRequestHeaders() {
    let headers = {};
    //Possibly add more headers
    await this.attachCSRFTokenToHeaders(headers); //Attach the csrf token to the headers of each request
    return headers;
}


static async logInManually(email, password, cb) {
    let requestBody = { email, password};
    axios.post(EndPoints.SIGN_IN, requestBody, {
        headers: await this.getRequestHeaders() //Attach the headers here
    }).then((response) => {
        cb(HttpSuccessDataHandler.getSuccessResponseData(response), null);
    }).catch((e) => {
        cb(null, HttpErrorHandler.spitHttpErrorMsg(e));
    });
}

But the server still keeps throwing the usual:

ForbiddenError: invalid csrf token

Here is a snippet into my server setup

const csrf = require('csurf');
const cookieParser = require('cookie-parser');
const session = require('express-session');

....

initMiddleWare() {
        app.use(express.static('./static'));
        app.use(express.json());
        app.use(express.urlencoded({ extended: true }));
        app.use(cookieParser())
        app.use(session({
            secret: Constants.SESSIONS_SECRET,
            resave: false,
            saveUninitialized: false
        }));
        app.use(busboy({
            highWaterMark: 2 * 1024 * 1024,
            limits: {
                fileSize: maxFileSize,
            }
        }));
        app.use(csrf({ cookie: true }))
    }


 //Then somewhere in my routes, here is the route that provides the csrf token
.....
   app.get(Routes.CSRF_TOKEN, function (req, res) {
        res.send({ csrfToken: req.csrfToken() });
       });
....
ololo
  • 1,326
  • 2
  • 14
  • 47

1 Answers1

0

Because of csrf({cookie: true}), the CSRF token is bound to a cookie. The axios.post request must contain not only the CSRF token in a header, but also the cookie that was received with the response to the previous axios.get request. Your code sets only the header. Unless axios handles the cookies automatically (like a browser would do), you must include client-side code for handling them as well.

Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31