Skip to content

Instantly share code, notes, and snippets.

@enygma
Created May 14, 2012 21:41
Show Gist options
  • Save enygma/2697434 to your computer and use it in GitHub Desktop.
Save enygma/2697434 to your computer and use it in GitHub Desktop.
Hashing in REST Requests (with FuelPHP)
<?php
class Controller_User extends Controller_Rest
{
protected function validateHash()
{
$request = file_get_contents('php://input');
$requestHeaders = apache_request_headers();
if (!isset($requestHeaders['X-Auth']) || !isset($requestHeaders['X-Auth-Hash'])) {
$this->response('fail!',401);
} else {
// we have the headers - let's match!
$user = Model_User::find()->where('public_key',$requestHeaders['X-Auth'])->get_one();
if ($user !== null) {
$hash = hash_hmac('sha256',$request,$user->private_key);
return ($hash == $requestHeaders['X-Auth-Hash']) ? true : false;
} else {
return false;
}
}
}
public function post_index()
{
// return the user details here....
}
public function router($resource, array $arguments)
{
if ($this->validateHash() == false) {
$resource = 'error';
$arguments = array('Not Authorized',401);
}
parent::router($resource,$arguments);
}
}
// and the client.....
$privateKey = 'caa68fb2160b428bd1e7d78fcf0ce2d5';
$publicKey = '01fa456c4e2a2bc13e5c0c4977297fbb';
$data = '{"username":"happyFunBall"}';
$hash = hash_hmac('sha256',$data,$privateKey);
$headers = array(
'X-Auth: '.$publicKey,
'X-Auth-Hash: '.$hash
);
$ch = curl_init('http://mysite.localhost:8080/user');
curl_setopt($ch,CURLOPT_HEADER,true);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
echo "\n\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment