Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using csurf with react-server

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)?

like image 921
feychu Avatar asked Jan 04 '17 13:01

feychu


People also ask

How do I generate CSRF tokens for a react client?

Let's say you have a NodeJS and Express back end that interacts with your React client. You can install a library called csurf that's used to generate CSRF tokens, and you can send them to your client through an endpoint. Now you need to add the following endpoint.

What is CSURF in Node JS?

Csurf module in Node.js prevents the Cross-Site Request Forgery (CSRF) attack on an application. By using this module, when a browser renders up a page from the server, it sends a randomly generated string as a CSRF token.

How does CSURF work in Laravel?

The csurf function takes an optional options object that may contain any of the following keys: Determines if the token secret for the user should be stored in a cookie or in req.session. Storing the token secret in a cookie implements the double submit cookie pattern .

How do I send headers with X-Csrf-Token in react?

I'm using Axios in this example, but you can also use Fetch API to send valid headers with the X-CSRF-Token attached to the request. Let's say your minimal profile page component in React looks like this. You can then call the getCSRFToken function inside the useEffect as shown:


1 Answers

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 }); 
like image 200
Tim Tutt Avatar answered Oct 24 '22 19:10

Tim Tutt