node.jscsrfcsrf-token

Node.js: CSRF is not getting invalidated after use


I am facing a really annoying issue that the CSRF security token is not getting invalidated after it has been used.

I tried to submit the form several times with the same values and csrf token but it worked. Whereas, I should have received the 403 error.

import csrf from 'csrf';
import express from 'express';
...

const App = express();

// CSRF tokens
const tokens = new csrf({ cookie: true });
const csrfToken = tokens.secretSync({ saltLength: 128 });

App.use((req, res, next) => {
    ...

    // Validating CSRF token
    if (
        (['get', 'options'].includes(req.method.toLowerCase()) === false) &&
        ! tokens.verify(csrfToken, req.body._csrf) &&
        ! tokens.verify(csrfToken, req.headers['x-csrf-token'])
    ) {
        throw new Error('CSRF: Invalid or missing token');
    }

    req.csrfToken = tokens.create(csrfToken);

    next();
});

...

controller.js

const csrfToken = async (req, res) => await res.json({
    csrf: req.csrfToken
});

export {
    csrfToken,
};

Sending requests Application request log


Solution

  • It seems that I was under the wrong impression that API's data submission routes, such as: POST, PUT, PATCH, etc., should also be protected with the CSRF token in order to enhance the security, just like posting a form via a browser window.

    However, while searching for the answer, I came to know that unlike form submission via a web browser, the api data submission do not require the csrf protection as they typically do not rely on the cookies to insure the identity of the user.

    If you like to read more then follow this link to the question