express.js CSURF cookie and header match, returning 403

狂风中的少年 提交于 2020-01-16 05:39:06

问题


I have a simple express server setup like:

  app.use(bodyParser.json());
  app.use(cookieParser());
  app.use(csurf({ cookie: true }));
  // routes
  app.use(Routes imported from another file);

The client is currently just a simple form in react. I am loading some initial data before the react app loads and the csrf cookie is being set there.

I have a simple function for parsing the csrf cookie client side. I'm proxying the express server in create-react-app so I can't just set a meta tag in the header.


const csrfToken = () => {
  const cookies = decodeURIComponent(document.cookie).split(';');
  const token = cookies.find(cookie => cookie.includes('_csrf'));

  if (token) {
    return token.split('=')[1]
  }
}

I am using fetch to send along data and the token

const response = await fetch(url, {
      credentials: 'include',
      method: 'POST',
      headers: {
        'Connection': 'keep-alive',
        'Content-Type': 'application/json',
        'X-CSRF-Token': csrfToken()
      },
      body: JSON.stringify({ ...body })
    });

I've tried commenting out the line that tells the app to use csurf and checking that everything is present on the request. I can verify that the cookie and the header are matching in every request I send. Everything seems correct, but I am still getting a 403 error so I must be missing something. I'm at a lost to what it could be and all I could find googling is other people setting up their apps very similarly.


回答1:


You are reading the content of the _csrf cookie and sending it back inside X-CSRF-Token header. This will not work.

The csurf middleware running inside Express has been configured by this code: app.use(csurf({ cookie: true })); to generate the _csrf cookie and send it to the client. The middleware expects you to:

  1. Generate the second piece of CSRF data on the server.
  2. Attach the second piece of data to the response sent to a client. As a result, the response arrives to the client with both the _csrf cookie and the second piece of data attached.
  3. Ensure the incoming request from the client has the same _csrf cookie and the second piece of data copied into one of the six predefined places/locations (such as 'X-CSRF-Token' header or another location).

See this answer for more details.



来源:https://stackoverflow.com/questions/59606019/express-js-csurf-cookie-and-header-match-returning-403

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!