Prevent Cross-Site Request Forgery (CSRF) Attacks

Learn how CSRF works and how to prevent CSRF attacks in your Web applications.
Read more…

Brought for you by @andrea.chiarelli

Share your thoughts about CSRF attacks and the techniques to prevent them!

In this example, a POST request is made to localhost:3000 from localhost:4000(attacker) right? I am very confused as to why the browser does not block this request because of Cross Origin, ie, throw a CORS error. I checked the server code for server.js, and I see no CORS header being set, and I checked the origin and referer of the POST request from :4000, and they both say localhost:4000.

Hi @borrowedlens,
Welcome and thanks for joining the Auth0 Community!

Regarding your question, the same-origin policy applies to Javascript: a script downloaded from server A can only make requests to server A.
By default, it doesn’t apply to HTML elements like forms, links, images, and so on. See this document for more details.

The attacker’s code shown in the article is as follows:

<form method="post" action="http://localhost:3000/user">
    <input type="hidden" name="username" value="The Attacker">
    <input type="hidden" name="email" value="theattacker@attacker.com">
</form>

<a href="#" onclick="document.forms[0].submit()">Visit this website!</a>

Here, the JavaScript code document.forms[0].submit() runs on the attacker’s website and the only thing it does is submit the form to the vulnerable website.
This form submission is legitimate because the remote server is not invoked by JavaScript. JavaScript simply simulates the click of the user on the submit button.

Consider that posting a form to another website is not a risk per se. It is like linking another website with parameters. Here, the risk comes from the session cookie sent along with the POST request, as explained in the article.

I hope this clarifies your doubts.