Cross-site request forgery

Cross-site request forgery or CSRF occurs when a victim visits an external web page, which submits a form back to the victim domain to perform some malicious action.

For instance::

The user may be tricked into visiting an external webpage under the control of an attacker. The external webpage will have a script on it which generates a fake form with a delete control and then submits it without user interaction. The form is submitted with the victim's cookies. Thus, the external website can delete any item.

The way we avoid this is by including a random token in the HTML before form submission, which then must be submitted intact during form submission. Thanks to JavaScript's "same origin" policy, the offsite script cannot read the random token from the form.

The code will look like this:

Every form which performs a write operation should be protected in this way.