我为PHP应用程序构建了一个宁静的API。目前,API只会接受json响应。请求,路由和响应都由框架处理,但我需要构建自定义的认证机制。
我想添加两项以增加安全性并避免重播攻击:时间戳和随机数。
除了这两个项目之外,我还希望进行一次完整性检查,以确保从安全性或可用性的角度来看,我没有错过任何其他显而易见的事情。
entity_id应该放在标题中而不是请求中吗?
这是我到目前为止的认证:
function authenticate_request()
{
$request = json_decode(file_get_contents('php://input'));
$request_headers = apache_request_headers();
if ( ! isset($request_headers['X-Auth']) OR ! isset($request_headers['X-Auth-Hash'])) {
return false;
}
$user = User::get_by('public_key', $request_headers['X-Auth']);
if ( ! $user) {
return false;
}
// every request must contain a valid entity
if (isset($request->entity_id) && $request->entity_id > 0) {
$this->entity_id = $request->entity_id;
} else {
return false;
}
$entity = Entity::find($this->entity_id);
if ( ! $entity) {
return false;
}
// validate the hash
$hash = hash_hmac('sha256', $request, $user->private_key);
if ($hash !== $request_headers['X-Auth-Hash']) {
return false;
}
return true;
}示例卷曲请求:
$public_key = '123';
$private_key = 'abc';
$data = json_encode(array('entity_id' => '3087', 'date_end' => '2012-05-28'));
$hash = hash_hmac('sha256', $data, $private_key);
$headers = array(
'X-Auth: '. $public_key,
'X-Auth-Hash: '. $hash
);
$ch = curl_init('http://localhost/myapp/api/reports/');
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);