[英]PHP rest API authentication
我正在為php應用程序構建一個restful API。 目前,API只接受並回復json。 請求,路由和響應都由框架處理,但我需要構建自定義身份驗證機制。
我想添加兩個項目以獲得額外的安全性並避免重放攻擊:時間戳和隨機數。
到目前為止,這是我的身份驗證:
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;
}
curl請求示例:
$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);
hash_hmac()
期望它的第二個參數是一個字符串,而是傳遞解碼的 JSON對象。 除此之外,您的方法似乎很標准。 entity_id
也應受到HMAC簽名的保護,因此我會將其保留在請求正文中,否則您的簽名計算會變得更加復雜,無法獲得實際收益。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.