cURL CSRF Token

后端 未结 3 1790
無奈伤痛
無奈伤痛 2020-12-30 17:57

I few months ago, my colleague created an calendar subscription by getting the work schedule. I believe he has done this by cURL.

Now I\'m building a website to have

相关标签:
3条回答
  • 2020-12-30 18:22

    The CSRF token field value is not fixed but is a randomly generated value for newly created sessions. You need a "clean" call to the webpage first to obtain a CSRF token value, only after that you can POST the username/password together with the CSRF token, as in:

    <?php
    
      $username = "myusername";
      $password = "mypassword";
      $url = "http://planner.a-mac.nl/employeeSchedule";
      $cookie= "koekje.txt";
      $ch = curl_init();
    
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/'.$cookie);
      curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/'.$cookie);
    
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      $response = curl_exec($ch);
      if (curl_errno($ch)) die(curl_error($ch));
    
      $doc = new DOMDocument();
      $doc->loadHTML($response);
      $token = $doc->getElementById("signin__csrf_token")->attributes->getNamedItem("value")->value;
    
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
      curl_setopt($ch, CURLOPT_POST, true);
    
      $params = array(
        'signin[username]' => $username,
        'signin[password]' => $password,
        'signin[_csrf_token]' => $token
      );
      curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
    
      curl_exec($ch);
    
      if (curl_errno($ch)) print curl_error($ch);
      curl_close($ch);
    ?>
    
    0 讨论(0)
  • 2020-12-30 18:23

    I have a feeling that you should be adding the token like this:

    $headers[] = 'X-CSRF-Token:' .  $token;
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    0 讨论(0)
  • 2020-12-30 18:44

    The idea behind CSRF defense is based around generating a unique token for each page load which you have to pass with the form.

    You will have to load the page with the form, extract the token from the page and pass that along with the POST request. Typically, after any attempt, the token is invalidated and you must request the form again to get a new token.

    The CSRF token is stored in the session, so the server can see if the one generated on the form matches the one supplied with the request sending the form.

    0 讨论(0)
提交回复
热议问题