6

I would like to add csurf as an express middleware inside the react-server for a universal app.

What I want to achieve is adding the csrf token to a hidden input in a form in the react component to maintain the same csrf protection flow a server-rendered website would provide, but within a SPA.

Is this technically possible within the react-server? If so, how can I pass the csrf token that is available in the response object to the react component via the page (ideally)?

feychu
  • 1,284
  • 1
  • 14
  • 33

1 Answers1

2

I actually ran into the same problem and luckily happened to come across the solution here: https://github.com/kriasoft/react-starter-kit/issues/1142

to use it just do:

app.use(csrf({ cookie: true, value: (req) => (req.cookies.csrfToken) }));

and then for every get request set a cookie with the csrf token:

res.cookie('csrfToken', req.csrfToken ? req.csrfToken() : null, { sameSite: true, httpOnly: true }); 
Tim Tutt
  • 184
  • 7
  • Thanks for pointing this out, it seems to be a fairly generic solution so it may work in a react-server context as well. – feychu Jul 20 '17 at 20:59
  • I don't get what the point of this is though. If you're auto setting the token in every request, without receiving it from the client, its pretty much useless – alex067 Oct 17 '20 at 01:34
  • I think that the custom `value` function that checks for the CSRF token shouldn't look inside the cookies, but in the body or in the header of the request, as per [default behaviour in the csurf docs](https://www.npmjs.com/package/csurf#value), otherwise checking the cookie lets the server prone to the CSRF attack you are trying to defend from! – Kenna Oct 22 '20 at 10:40