Secure AuthSub in PHP


A helper for sending a signed HTTP GET request in PHP.

// upgrade a single-use AuthSub token
$response = signedGET('https://www.google.com/accounts/AuthSubSessionToken', $singleUseToken);

// fetch Calendar data
$response = signedGET('http://www.google.com/calendar/feeds/default/allcalendars/full', $sessionToken);

<?php
function signedGET($requestURL, $token) { 
  $privKeyFilePath = "../myrsakey.pem";
  $timestamp = time();
  $nonce = md5(microtime() . mt_rand()); 
  $sigalg = 'rsa-sha1';
  
  // construct the data string
  $data = "GET $requestURL $timestamp $nonce";
  
  // get rsa private key
  $fp = fopen($privKeyFilePath, "r");  
  $priv_key = fread($fp, 8192);
  fclose($fp);                                

  // compute signature
  $privatekeyid = openssl_get_privatekey($priv_key);
  openssl_sign($data, $signature, $privatekeyid, OPENSSL_ALGO_SHA1);
  openssl_free_key($privatekeyid);

  $curl = curl_init($requestURL);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_FAILONERROR, true);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  
  // Set Authorization header 
  $sig = base64_encode($signature);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array(
      "Authorization: AuthSub token=\"$token\" data=\"$data\" sig=\"$sig\" sigalg=\"$sigalg\"")
  ); 
  
  $result = curl_exec($curl);
  curl_close($curl);

  return $result;
}
?>

6 comments:

myObis said...

Thank you for this.
Is there a tool you would recommend to generate the .pem keys ?

Eric (Google) said...

openssl works great:
http://code.google.com/apis/gdata/authsub.html#Registered

Unknown said...

Eric, thank you very much for that tips

LSB_sreeja said...

can I use the signedGET to get the private/ protected blogs

Please suggest

JAldo said...

Way the nonce should be generated has been changed. Using the md5 might not be appropriate any longer.

"nonce: a random 64-bit, unsigned number encoded as an ASCII string in decimal."

Paresh said...

Hey friend,
What is value of $signature in line no 18
And i Got error :
Call to undefined function openssl_get_privatekey()
please help me..