I have a Nodejs app with React in front. I implemented my csrf like:
// initial-csrf.js
var csrf = require("csurf");
const csrfProtection = csrf({});
module.exports = {
csrfProtection,
};
//Server.js
app.use(csrfProtection); // It goes after app.use(appSession);
// Session controller
const csrfToken = (req, res) => {
res.send(req.csrfToken());
};
// Initial express session
var appSession = session({
store: new postgresSession({
pool: sessionDBaccess,
tableName: "sessions",
}),
name: "mCookie",
secret: "my-secret"
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7,
sameSite: true,
secure: false,
},
});
}
In React side : whenever I send a request I do like :
handleCreate() {
const csrf_data = {};
const csrf_response = callAxios(
"/api/sessions/csrfToken",
"GET",
csrf_data,
);
csrf_response.then((csrf_res) => {
const data = {
// some data
};
const response = callAxios("/api/sessions", "POST", data, csrf_res.data);
response.then((res) => {
if (res) {
if (res.data) {
// Some functions
} else {
if (res.response) {
// Some functions
}
}
}
});
});
}
This configuration works very well if there is one instance of the app (one pod). If I create multiple replicas from the app in my kubernetes cluster. I get CSRF invalid error. In fact I double check and my csrftoken is in session table in the database. Any ideas?