2019-01-14 16:19
浏览 126


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:


<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" />



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

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?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • drzrdc1766788 2019-01-14 16:23

    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.

    解决 无用
    打赏 举报
  • dre26973 2019-01-14 16:27

    CSRF is an attack, where the victim is logged in your site (has a session cookie), when you have no session then there is no CSRF needed. The victim visits an evil other website with the same browser. This site can now make a post request to your site (with the cookie and therefore login of the victim), which you can prevent with CSRF Token, because while an evil site can send requests with cookies, it can not read the responses of requests (Same origin policy). You can turn of this behavior in your (personal) Browser, but it is enabled by default, because some applications depend on it.

    解决 无用
    打赏 举报