Do I need a CSRF token for jQuery .ajax()?

后端 未结 4 1417
野趣味
野趣味 2020-12-08 07:20

So I\'ve got a basic .ajax() POST method to a PHP file.

What security measures do I need?

A few posts around were mentioning using a hidden MD5 input field t

4条回答
  •  不思量自难忘°
    2020-12-08 08:01

    Strictly, no token is needed, but you should still protect any functions that change state against CSRF.

    CRSF is most definitely a risk, even though the request is made via AJAX. This is because AJAX requests can be passed cross-domain - the Same Origin Policy only guards against reads, not writes. And also a traditional form might be able to send exactly the same POST request as your AJAX does, and your current server-side code might not detect this.

    One simple way of allowing your server-side code to detect whether the request has come from your own site is by adding a header that is sent with the AJAX request. It is important that your server-side code checks for the presence of this header. No random token is necessarily needed.

    This works because:

    • HTML forms cannot have custom headers added to them by an attacker.
    • Custom headers cannot be passed cross-domain without CORS being enabled.

    For a defence against any future developments on the web, it might be a good idea to also implement a random token. This would need to be tied to the current user session in some way. It isn't currently exploitable if the token isn't implemented, but in the web's long and twisted history, lack of tokens could be exploited by Flash and other browser plugins. In a perfect world, HTML5 and the living standard should mean that plugins like these are a thing of the past, however, who knows for sure what is around the corner so to add defence-in-depth and to future proof, tokens are also recommended.

    More info: What's the point of the X-Requested-With header?

提交回复
热议问题