0

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?

1
  • I don't know csurf in enough detail, but my guess is that the token is bound to the hostname. When a different replica in k8s receives the token, the hostname mismatches and the token is not validated. If this is correct and you have n replicas with round robin load balancing, every nth request will succeed. Commented Jan 26 at 20:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.