I use Ajax (jQuery) and the POST method to update data in the database. I do the following:
- Get data from the form: user_id, entry_id, content,...
- Send them to a URL which will process the data.
- If the data is valid, we will record them in our database.
I do not know how to verify that the user sends data from my website and not from other places. Please help me solve this problem. Thanks !
You're trying to defend against CSRF attacks.
The standard defense is to have a require a token in the POST that is retrieved from a different AJAX request. Because of the browser's cross-domain defenses, Javascript that is outside of your domain will not be able to get a token.
There are several issues here:
- Authentication and authorisation of the user who is doing the operation
- Protection against CSRF.
Decide which you need to do. The first should be able to be handled by cookies, HTTP authentication (which the browser sends for AJAX requests too) or some custom method (e.g. an extra parameter containing authentication)
CSRF is a different matter, but you can quite easily avoid it by ensuring that the request really came in via AJAX, not via a normal form-post. This should be achievable by tacking on an extra header which someone cannot add by making a HTTP form (NB: Not all headers can be added by Javascript, try using an X-Header).
Another possibility is to not use a form-encoded post in the first place; if you expect a JSON object in the body, that cannot come from another site, as browsers will not send it via a HTTP POST normally.