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.

Bharath Pabba
  • 1,725
  • 5
  • 16
  • 24

1 Answers1

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.

blueOwl
  • 56
  • 4
  • but the domain name can be easily changed right. It won't be a perfect solution to mitigate csrf attack – Bharath Pabba Apr 07 '20 at 10:34
  • 1
    correct, CSRF-Tokens might be a better solution. see https://stackoverflow.com/questions/5207160/what-is-a-csrf-token-what-is-its-importance-and-how-does-it-work – blueOwl Apr 07 '20 at 10:45