Craig
Craig

Reputation: 8294

Build an OAuth request for use with CURL in PHP

I'm trying to use OAuth in PHP to communicate with an external server. This is a sever to server function with nothing specific to any user, thus all the tokens and secrets are taken care of it's just fetching the protected resource I have to deal with. That and the proxy.

I can't see how to direct PHP's OAuth through a proxy but we already have a curl service (within our Symfony2 application) that deals with it appropriately so I'd like to just use OAuth to generate the authentication header and attach that to a regular curl get/post/put. I see the generateSignature function but I'm not sure how to apply that to the curl headers.

Upvotes: 1

Views: 4188

Answers (1)

Craig
Craig

Reputation: 8294

I found out that setting the headers in CURL is pretty easy

$oauth = new OAuth($this->consumerKey,$this->consumerSecret);

$oauth->setToken($this->token,$this->tokenSecret);
$url = $this->serviceUrl.'/locations/getlocations';
$nonce = mt_rand();
$timestamp = time();

$oauth->setTimestamp($timestamp);
$oauth->setNonce($nonce);

$sig = $oauth->generateSignature('GET',$url);

$header = array
 (
  'Content-Type: '.$ct,
  'Connection: keep-alive',
  'Keep-Alive: 800000', 
  'Expect:'
  );    
$header[] = 'Authorization: OAuth '.
            'oauth_consumer_key="'.$this->consumerKey.'"'.
            ',oauth_signature_method="HMAC-SHA1"'.
            ',oauth_nonce="'.$nonce.'"'.
            ',oauth_timestamp="'.$timestamp.'"'.
            ',oauth_version="1.0"'.
            ',oauth_token="'.$this->token.'"'.                      
            ',oauth_signature="'.urlencode($sig).'"'
            ;

And then with CURL

curl_setopt($ch,CURLOPT_HTTPHEADER, header);

Upvotes: 3

Related Questions