Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protect ajax posts? [closed]

Tags:

ajax

php

I have a form that users use to add their email address and name to sign up for a newsletter.

On submit an ajax request transmits the data to my database.

Should I use any sort of protection to stop someone else adding entries to the database, eg. if another site linked their form to my ajax request url, then they would be adding data to my database.

How can I stop this?

like image 833
panthro Avatar asked Sep 09 '13 13:09

panthro


People also ask

How can I make AJAX request secure?

There are some methods to secure AJAX calls and I give you a simple solution. This one use php session where a random key is generated and saved in session, then used in AJAX request to validate call request. The new url endpoint is http://www.myapp.ext/ajax/myplugin?skey=<Random key> .

Is AJAX post secure?

An AJAX call can be secured the same way any HTTP request can be secured. First of all, use POST as opposed to GET to hide any sensitive parameters from the URL. Secondly, cross check all your requests for CSRF(Cross-Site Request Forgery) by using a CSRF token.

Do AJAX calls keep session alive?

Yes it's safe. As far as load, that's up to your hardware and how you write it, but it has no worse effect than users refreshing the page (arguably less considering the overhead of an AJAX call over a standard page load). You can adjust the timeout in the web.


1 Answers

If you're really serious about it:

  • generate a random number for each page, and add it to the form as a hidden field ( and in $_SESSION )
  • on submission, check that the number matches

Even better, just create a random string, and only send its hash - if you match the hash you get from the form with the one generated from the original string, you have a valid request.

This will kill you caching though, so I cannot really recommend it as a "just do this" solution, depends on your volume.

like image 111
Nick Andriopoulos Avatar answered Oct 06 '22 18:10

Nick Andriopoulos