我一直在跟踪latest writeup from Microsoft,以生成用于Azure存储服务(尤其是Blob)的帐户级共享访问签名(SAS)。
每次我对Blob服务执行PUT
请求时,都会收到403
响应,并显示以下消息:
服务器无法验证请求。确保值 授权标头的格式正确,包括签名。
这是我生成签名的功能:
use MicrosoftAzure\Storage\Common\Internal\StorageServiceSettings;
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
public function generateUploadLink($container, $folder, $filename)
{
# get account settings
$settings = StorageServiceSettings::createFromConnectionString(AZURE_BLOB);
$accountName = $settings->getName();
$accountKey = $settings->getKey();
# define start and expire datetime stamps (ISO 8601)
$startTime = (new DateTime('GMT'))->modify('-2 days')->format('Y-m-d\TH:i:s\Z');
$expireTime = (new DateTime('GMT'))->modify('+2 days')->format('Y-m-d\TH:i:s\Z');
$parameters = [];
$parameters[] = $accountName; # account name
$parameters[] = 'wac'; # permissions
$parameters[] = 'b'; # service
$parameters[] = 'sco'; # resource type
$parameters[] = $startTime; # start time
$parameters[] = $expireTime; # expire time
$parameters[] = ''; # accepted ip's
$parameters[] = 'https,http'; # accepted protocol
$parameters[] = '2018-03-28'; # latest microsoft api version
# implode the parameters into a string
$stringToSign = utf8_encode(implode("\n", $parameters));
# decode the account key from base64
$decodedAccountKey = base64_decode($accountKey);
# create the signature with hmac sha256
$signature = hash_hmac("sha256", $stringToSign, $decodedAccountKey, true);
# encode the signature as base64
$sig = urlencode(base64_encode($signature));
# construct the sas (shared access signature)
$sas = "sv=2018-03-28&ss=b&srt=sco&sp=wac&se={$expireTime}&st={$startTime}&spr=https,http&sig={$sig}";
# create client
$blobClient = BlobRestProxy::createBlobService(AZURE_BLOB);
# generate upload link
$blobUrlWithSAS = sprintf('%s%s?%s', (string)$blobClient->getPsrPrimaryUri(), "{$container}/{$folder}/{$filename}", $sas);
# return upload link
return $blobUrlWithSAS;
}
我的输出示例如下所示–向此URL发起PUT
请求时,它失败并显示上述错误消息。
https://batman.blob.core.windows.net/payroll-enroll/2019/test.txt?sv=2018-03-28&ss=b&srt=sco&sp=wac&se=2019-02-04T03:44:51Z&st=2019-01-31T03:44:51Z&spr=https,http&sig=ox7RdKGTKRYvGz2u9ScFv4TP4ZfduKxFhYdpvJKjE4A%3D
通过比较,如果我直接从Azure门户生成帐户级别的共享访问签名,则它看起来像这样-向该URL发起PUT
请求时,它会成功。
https://batman.blob.core.windows.net/payroll-enroll/2019/test.txt?sv=2018-03-28&ss=b&srt=sco&sp=wac&se=2019-02-02T16:29:17Z&st=2019-02-02T08:29:17Z&spr=https,http&sig=omPc4ZwEdefDoHKqA4TqVOm3NUW%2BcKcNqTuD1hq94VU%3D
除了开始和到期时间,我看不出两者之间的差异。顺便说一句,我还将注意到,我尝试使用azure-storage-php包生成具有相同结果(无法验证请求)的服务级别SAS。
我已确认或尝试以下操作:
$accountName
和$accountKey
返回正确的值now
,UTC
和GMT
中的每一个作为DateTime()
的参数*
)CORS设置应用于我的存储帐户,用于ALLOWED METHODS
,ALLOWED ORIGINS
,ALLOWED HEADERS
和EXPOSED HEADERS
Secure transfer required
(同时允许http
和https
)我很困惑。
我的问题:构建SAS时我做错了什么,为什么我继续收到与身份验证相关的请求失败?
答案 0 :(得分:1)
请更改以下代码行:
$stringToSign = utf8_encode(implode("\n", $parameters));
到
$stringToSign = utf8_encode(implode("\n", $parameters) . "\n");
本质上,您需要附加一个额外的换行符。