Beep
Beep

Reputation: 1

cURL X-CSRF Token Issue

I have this PHP proxy using cURL (below). Whenever it gets a POST the header X-CSRF token is set to null. The X-CSRF token is the only difference in the POST header between using the proxy and not.

So I am wondering how to go about fixing it so that the X-CSRF token is set correctly as it would without using the proxy?

$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0');

$browserRequestHeaders = getallheaders();
$curlRequestHeaders = array();
foreach ($browserRequestHeaders as $name => $value) {
  $curlRequestHeaders[] = $name . ": " . $value;
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlRequestHeaders);


switch ($_SERVER["REQUEST_METHOD"]) {
  case "POST":
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents("php://input"));
  break;
  case "PUT":
    curl_setopt($ch, CURLOPT_PUT, TRUE);
    curl_setopt($ch, CURLOPT_INFILE, fopen("php://input"));
  break;
}

//Other cURL options.
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt ($ch, CURLOPT_FAILONERROR, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, 0);

// Cookie cURL options.
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); 
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);

//handle other cookies cookies
foreach ($_COOKIE as $k=>$v) {
  if(is_array($v)){
    $v = serialize($v);
  }
    curl_setopt($ch,CURLOPT_COOKIE,"$k=$v; domain=.$cookiedomain ; path=/");
  }

// Set the request URL.
curl_setopt($ch, CURLOPT_URL, $url);

// Make the request.
$response = curl_exec($ch);
curl_setopt($ch, CURLOPT_POST, 0);
$responseInfo = curl_getinfo($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
curl_close($ch);

Image showing headers https://i.sstatic.net/78fVV.jpg

Upvotes: 0

Views: 2255

Answers (2)

Beep
Beep

Reputation: 1

Had to proxy the $_SESSION id between client and servers in php.

Upvotes: 0

user4416936
user4416936

Reputation: 151

You're using AJAX calls and as your picture shows, the X-CSRF-Token header does not get set on those calls. You need to set it explicitly as explained in Adding X-CSRF-Token header globally to all instances of XMLHttpRequest();, e.g. with (copied from there):

(function() {
var send = XMLHttpRequest.prototype.send,
    token = $('meta[name=csrf-token]').attr('content');
XMLHttpRequest.prototype.send = function(data) {
    this.setRequestHeader('X-CSRF-Token', token);
    return send.apply(this, arguments);
};
}());

So the fix is not in PHP but in your AJAX calling code. Replace token = $('meta[name=csrf-token]').attr('content'); with code that obtains the CSRF token from your HTML.

Upvotes: 1

Related Questions