2012-09-11 162 views
3

我正在爲PHP應用程序構建一個寧靜的API。目前,API只會接受json響應。請求,路由和響應都由框架處理,但我需要構建自定義的認證機制。PHP rest API認證

爲了提高安全性並避免重放攻擊,我想添加兩個項目:時間戳和隨機數。

  1. 除了這兩個項目,我希望有一個全面的檢查,以確保我沒有錯過任何東西從一個安全性或可用性點真的很明顯。
  2. 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); 

回答

2

hash_hmac()預計其第二個參數是一個字符串,你通過你的代替解碼 JSON對象。除此之外,你的方法看起來很標準。 entity_id也應該受到HMAC簽名的保護,所以我會將它保留在請求主體中,否則您的簽名計算會變得稍微複雜一點,因爲沒有真正的收益。

+0

我傳遞json_encode到hash_hmac,而不是json_decode,所以我認爲那就OK了。使用這種方法是否意味着不能有API請求 - 因爲總是必須有CURL_POSTFIELDS? – JonoB

+0

您提到的'json_encode'不存在於您的發佈代碼中。使用您發佈的代碼很明顯,您無法向您的API發出GET請求,因爲您需要JSON POST正文中的entity_id'鍵,這在GET請求中永遠不會出現。除非您決定將整個JSON字符串作爲單個GET參數傳遞,否則您將需要針對GET請求使用完全不同的簽名算法。 – lanzz