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:
Am missing something?
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.