2

Below is the file structure of my MERN project.

|-Project
  |- client
  |- server

Client folder contains a react server. Client runs at localhost.client.com Server folder contains a code for the node.js server. Server runs at localhost.server.com

Whenever I'm making a request from the client to server. How can I mitigate the csrf attack? To make sure that the request made to the server is from the client and not from any other source.

1 Answer 1

2

Your issue might be covered in React frontend and REST API, CSRF.

There is an excellent article about CSRF and counter measures (with Angular in mind, but it is still the same problem). TL/DR:

  • use same-origin-policy or set Access-Control-Allow-Origin-header when needed
  • save XSRF-Token as secure cookie (unfortunately this requires an exta request - most times). Only code from your domain can access this value.
  • send that token as X-XSRF-TOKEN header value with your request to authorize the request

To make sure only your application can use the server api you can set the Access-Control-Allow-Origin value in the CORS / OPTIONS response header.

During development it usually is set to
Access-Control-Allow-Origin: *

for production you specify your domain / server name
Access-Control-Allow-Origin: localhost.client.com

To prevent spoofing the origin, you can use (Anti-)CSRF-Tokens. This are extra values attached to your request, which authenticate your request. This value can/should be saved in a secure cookie. csurf or JSON Web Tokens might be relevant for you. In your case CSRF-Tokens might require an extra request to your api to query the token.

Sign up to request clarification or add additional context in comments.

2 Comments

but the domain name can be easily changed right. It won't be a perfect solution to mitigate csrf attack
correct, CSRF-Tokens might be a better solution. see stackoverflow.com/questions/5207160/…

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.