Search code examples
phpcsrfcsrf-protectioncsrf-token

What is the sense of the CSRF Token protection?


I have read a lot about this and I still don't understand it. Let's say I have a domain with a form available only for authenticated users to post comments on some kind of content:

my_form.php

<form action="post_comment.php" method="post">
  <textarea name="comment"></textarea>
  <input type="hidden" name="csrf_token" value="<?php print $csrf_token; ?>" />
  <input type="submit" value="Post" />
</form>

post_comment.php

<?php

  if(!isset($_POST['csrf_token']) || !CSRFToken::validate($_POST['csrf_token'])){
    print "Invalid CSRF-Token!";
    exit;
  }
  [...]
?>

The post_comment.php will reject any request if the "csrf_token" token value is not sent or is not valid. So we are preventing attackers to use our post_comment.php.

BUT how to prevent the attacker to GET /my_form.php, read the csrf_token value from the form and POST to post_comment.php using it? What am I missing?


Solution

  • The CSRF token is random and unique per session. Hence, an attacker can get the value of this token that is linked to his/her own credentials, but not to that of a potential victim.