CSRF and RESTful APIs (symfony2, php)

I am developing a RESTful API using php / symfony2.

Symfony2 comes with CSRF protection out of the box, and it works great when using normal form data (it passes the CSRF token to the form and, when it is sent back, expects the same token that is built into the form).

However, this solution is not suitable for the purpose if you are developing a RESTful API where my interaction between the backend interface is pure JSON. Because of this, I disabled CSRF.

I know that the CSRF token is not safe, so I'm wondering what is the best way to have CSRF with the RESTful API.

One idea is to have a specific URL, for example. / api / generate / csrf, which can be called by the interface, and then add the token to the json request. It doesn’t sound like anyone can generate the safest way, like a token.

What is the best way to approach the CSRF issue when developing a RESTful API.

Cheers, Richard

+6
source share
2 answers

Remember that you only need CSRF protection when your REST client uses session-based authentication, otherwise CSRF protection will not help you.

If your requests use session-based authentication, I would include the CSRF token as a header. Sort of:

CSRF-Token: dfsa0jr3n2io20a; 
+1
source

I am also working on this issue. Here is my original question .

I have a theoretical solution, but I'm not quite sure if this will work. Maybe someone can comment.

  • Add CSRF TOKEN to API response cookies, readable by the JS application;
  • Submit it with a request as an X-CSRF-TOKEN header value by the JS application;
  • Check out CSRF TOKEN on the API.
0
source

All Articles