简体   繁体   中英

CSRF and RESTful API (symfony2, php)

I'm developing RESTful API using php/symfony2.

Symfony2 comes with CSRF protection out of the box and it works fine when using normal form data (it passes CSRF token to the form and when posted back it expects the same token which is embeded in the form).

Nonetheless this solution is not fit for purpose if you develop RESTful API, where my communication between backend<->frontend is purely JSON based. Because of that I disabled CSRF.

I'm aware not having CSRF token is not safe, so I'm wondering what's the most optimal way to have CSRF with RESTful API.

One idea in mind is to have specific URL eg /api/generate/csrf, which can be called by frontend then append token to json request. It doesn't sound as the safest way as token technically could be generated by anyone.

What's the best way to approach CSRF problem when developing RESTful APIs.

Cheers, Richard

Remember that you only need CSRF protection when your REST client is using session based authentication, otherwise CSRF protection won't help you.

If your requests DO use session based authentication, I would include the CSRF token as a header. Something like:

CSRF-Token: dfsa0jr3n2io20a;

I'm working on this issue too. Here is my original question .

I have a theoretical solution so far, but I'm not quite sure it will work. Maybe somebody can comment.

  1. Add the CSRF TOKEN to the API response cookie readable by the JS application;
  2. Send it with the request as X-CSRF-TOKEN header value by the JS application;
  3. Verify the CSRF TOKEN on the API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM