3

我正在为 php 应用程序构建一个宁静的 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);
4

1 回答 1

2

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

于 2012-09-11T21:21:31.883 回答