PHP rest API身份验证


PHP rest API authentication

我正在为php应用程序构建一个restful API。目前,API将只接受并使用json进行响应。请求、路由和响应都由框架处理,但我需要构建一个自定义的身份验证机制。

为了提高安全性和避免重放攻击,我想添加两项:时间戳和随机数。

  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);

hash_hmac()希望它的第二个参数是字符串,而您正在传递解码的JSON对象。除此之外,你的方法似乎很标准。entity_id也应该受到HMAC签名的保护,所以我会把它保存在请求体中,否则你的签名计算会变得有点复杂,没有真正的好处。