Search code examples
javascriptajaxsecurityddos

Prevent AJAX flooding in Javascript


My site has a Javascript method that makes an AJAX request to add an item to cart without reloading the page and making a simple notification.

 AddToCart()

However, using any Javascript console, I found you can flood this request with a simple statement:

while (true) {AddToCart()}

And eventually lock the server until the browser crashes. A more stable browsing environment could probably even lock the server indefinitely. So what would be the best way to protect against such an attempt?


Solution

  • Perhaps you should just define the function in a private namespace?

    (function() {
       function AddtoCart(){};
    })();
    

    That way you can't reference it through the console.

    This of course is not bulletproof as anyone could just replicate the code or make HTTP requests to the URI.

    You can't stop the HTTP requests but you can stop the page processing data possibly by implementing CSRF tokens so that it won't do the heavy processing unless the CSRF token matches, which is generated from your page which creates the CSRF based on variables like timestamp and such, so it can't be (easily?) reproduced.