PHP 为 Blob 存储创建有效的 Azure 签名

PHP Create Working Azure Signature For Blob Storage

有人可以提供一个工作示例 (php) 来创建在为 2015 年仍在运行的 Microsoft Azure Blob 服务构建“Shared Access Signatures URL”时所需的签名吗? 我在互联网上找到的所有示例和教程都使用旧的非官方 azure sdk,或者从提供的代码创建的签名不起作用,因为我总是收到以下错误:

<Error>
    <Code>AuthenticationFailed</Code>
    <Message>Server failed to authenticate the request. Make sure the value of  Authorization header is formed correctly including the signature. RequestId:2c406e11-0001-00b1-3a5a-0eb263000000 Time:2015-10-24T12:46:34.5256055Z</Message>
    <AuthenticationErrorDetail>Signature fields not well formed.</AuthenticationErrorDetail>
</Error>

这是我试过的代码:this and this

这就是我现在的代码:

$key = "myKeyBase64==";
$sig = getSASForBlob("accName","containerName", "abc.mp3", "b", "r", date("c", time() + 30000), $key);
$url = getBlobUrl("accName","containerName","abc.mp3","b","r",date("c", time() + 30000),$sig);

echo($url);

function getSASForBlob($accountName,$container, $blob, $resourceType, $permissions, $expiry,$key){
     /* Create the signature */
     $_arraysign = array();
     $_arraysign[] = $permissions;
     $_arraysign[] = '';
     $_arraysign[] = $expiry;
     $_arraysign[] = '/' . $accountName . '/' . $container . '/' . $blob;
     $_arraysign[] = '';
     $_arraysign[] = "2014-02-14"; //the API version is now required
     $_arraysign[] = '';
     $_arraysign[] = '';
     $_arraysign[] = '';
     $_arraysign[] = '';
     $_arraysign[] = '';

     $_str2sign = implode("\n", $_arraysign);

     return base64_encode(
     hash_hmac('sha256', urldecode(utf8_encode($_str2sign)), base64_decode($key), true)
     );
}

 function getBlobUrl($accountName,$container,$blob,$resourceType,$permissions,$expiry,$_signature){
     /* Create the signed query part */
     $_parts = array();
     $_parts[] = (!empty($expiry))?'se=' . urlencode($expiry):'';
     $_parts[] = 'sr=' . $resourceType;
     $_parts[] = (!empty($permissions))?'sp=' . $permissions:'';
     $_parts[] = 'sig=' . urlencode($_signature);
     $_parts[] = 'sv=2014-02-14';

     /* Create the signed blob URL */
     $_url = 'https://'
     .$accountName.'.blob.core.windows.net/'
     . $container . '/'
     . $blob . '?'
     . implode('&', $_parts);

     return $_url;
 }

我发现您的代码存在一个问题:

本质上,您的到期时间格式不正确。您的到期时间应采用 YYYY-MM-DDTHH:mm:ssZ 格式。

请尝试以下代码:

$expiry = gmdate("Y-m-d\TH:i:s\Z", time() + 30000);
$sig = getSASForBlob("accName","containerName", "abc.mp3", "b", "r", $expiry, $key);
$url = getBlobUrl("accName","containerName","abc.mp3","b","r",$expiry,$sig);

您无需更改 getSASForBlobgetBlobUrl 功能。

我尝试使用上面的代码并能够使用 SAS 下载 blob URL。