简体   繁体   English

CSRF和RESTful API(symfony2,php)

[英]CSRF and RESTful API (symfony2, php)

I'm developing RESTful API using php/symfony2. 我正在使用php / symfony2开发RESTful API。

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). Symfony2具备开箱即用的CSRF保护功能,并且在使用常规表单数据时可以正常工作(它将CSRF令牌传递到表单,并且在回发时它期望嵌入在表单中的令牌相同)。

Nonetheless this solution is not fit for purpose if you develop RESTful API, where my communication between backend<->frontend is purely JSON based. 但是,如果您开发RESTful API,则此解决方案不适合您的目的,因为我的backend <-> frontend之间的通信完全基于JSON。 Because of that I disabled CSRF. 因此,我禁用了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. 我知道没有CSRF令牌是不安全的,所以我想知道使用带有RESTful API的CSRF的最佳方法是什么。

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. 想到的一个想法是拥有特定的URL,例如/ api / generate / csrf,可以由前端调用,然后将令牌附加到json请求。 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. 开发RESTful API时,解决CSRF问题的最佳方法是什么。

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. 请记住,只有当REST客户端使用基于会话的身份验证时,才需要CSRF保护,否则CSRF保护将无济于事。

If your requests DO use session based authentication, I would include the CSRF token as a header. 如果您的请求确实使用基于会话的身份验证,则将CSRF令牌作为标头包含在内。 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; 将CSRF TOKEN添加到JS应用程序可读的API响应cookie中;
  2. Send it with the request as X-CSRF-TOKEN header value by the JS application; JS应用程序将其与请求一起作为X-CSRF-TOKEN标头值发送;
  3. Verify the CSRF TOKEN on the API. 验证API上的CSRF令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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