Search code examples
javascriptsecuritycsrfcsrf-protection

How to does the token prevent csrf attack?


I have read about CSRF and how the Unpredictable Synchronizer Token Pattern is used to prevent it. I didn't quite understand how it works.

Let's take this scenario :

A user is logged into a site with this form:

<form action="changePassword" method="POST">
   <input type="text" name="password"><br>
   <input type="hidden" name="token" value='asdjkldssdk22332nkadjf' >
</form>

The server also stores the token in the session. When the request is sent it compares the token in the form data to the token in the session.

How does that prevent CSRF when the hacker can write JavaScript code that will:

  1. Send a GET request to the site
  2. Receive html text containing the request form.
  3. Search the html text for the CSRF token.
  4. Make the malicious request using that token.

Am missing something?


Solution

  • The attacker can't use JavaScript to read the token from the site, because it would be a cross-origin request and access to the data from it is blocked (by default) by the Same Origin Policy (MDN, W3C).

    Take this for example:

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://google.com");
    xhr.addEventListener('load', function (ev) {
        console.log(this.responseText);  
    });
    xhr.send();

    The JS console reports:

    XMLHttpRequest cannot load http://google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource.