views:

186

answers:

2

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 !

+5  A: 

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.

SLaks
they could run bot to get the token. so the best way I think is to include cookie also, beside, if you don't want the attack, go for a captcha.
DucDigital
@DucDigital: What are you talking about?
SLaks
+1  A: 

There are several issues here:

  1. Authentication and authorisation of the user who is doing the operation
  2. 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.

MarkR
+1 for your opening, -1 for your last two paragraphs: You need to defend against attacks that are HTTP-based, but not necessarily browser-based. We can't assume any theoretical attackers will be using just a browser. Link spammers are 'way more advanced than that, as one example.
T.J. Crowder
Cross-site request forgery is where your legitimate users are tricked into using their own browser (with its authentication and cookies) into making unintended requests. Using a non-form based POST or custom headers avoids this specific attack.
MarkR