Max
Max

Reputation: 21

Sails 1.4.0 CSRF Token sent from React App getting rejected 403

for the last three days I got stuck at this problem and it is getting very frustrating. I don't know what else to try.

I am running a Sails app on localhost:1337 and a create-react-app on localhost:3000.

I enabled csrf on the backend and followed the sails documentation to implement it. I have created the route 'GET /grant-csrf-token': { action: 'security/grant-csrf-token' } and it works fine, I get the token. If I use postman the token is accpeted and my login form works.

In React however, I receive the token but I get 403 Forbidden error when I submit the post request to login.

    useEffect(async () => {
    let csrfToken;
    try {
      let csrfTokenRequest = await Axios.get(
        `${state.serverUrl}/grant-csrf-token`
      );

      csrfToken = csrfTokenRequest.data["_csrf"];

      dispatch({
        type: "csrf",
        value: csrfToken,
      });

    } catch (err) {
      dispatch({
        type: "flashMessage",
        value: "There was an error.",
      });
    }
  }, []);

I tried various ways to send the token with my post request:

await Axios.post(
        `${appState.serverUrl}/login`,
        {
          emailAddress,
          password,
          _csrf: appState.csrf,
        },
        { withCredentials: true }
      );

I also tried setting it as a default header like so:

Axios.defaults.headers.post["X-CSRF-Token"] = appState.csrf;

and set cors allowRequestHeaders parameter to allowRequestHeaders: 'content-type, X-CSRF-Token',

I also tried sending it as a query parameter

`/login?_csrf=${encodeURIComponent(appState.csrf)}`

I also tried various cors settings inside Sails, currently it is setup like so:

cors: {
    allRoutes: true,
    allowOrigins: [
        'http://localhost:3000',
    ],
    allowCredentials: true
}

So just to clarify once again:

Upvotes: 1

Views: 333

Answers (1)

Jorge Vargas
Jorge Vargas

Reputation: 301

Could you try something like that:

Send the csrf in header and allow Sails to process the request header.

// config/security.js
cors: {
    allRoutes: true,
    allowOrigins: ['http://localhost:3000'],
    allowCredentials: true,
    allowRequestHeaders: ['content-type', 'x-csrf-token', 'authorization'],
  },

Upvotes: 0

Related Questions