使用Azure Rest API列出Blob返回403 Forbidden,Shared Key签名问题排查
问题分析与修复
你的403错误源于Shared Key签名构建的两处关键错误:
错误1:规范资源(CanonicalizedResource)格式错误
你在/{accountName}/{containerName}后多了一个空格,这会导致签名计算与服务端校验不匹配,是引发403的直接原因之一。
错误2:签名字符串(stringToSign)结构错误
当使用x-ms-date请求头时,stringToSign中的Date字段必须留空;同时x-ms-date和x-ms-version需要作为规范请求头加入到stringToSign中,且规范头需按头名称的小写字母顺序排序(x-ms-date在前,x-ms-version在后)。
修正后的代码
// Build the authorization signature var requestDate = DateTime.UtcNow.ToString("R"); // 修复:移除containerName后的空格,确保规范资源格式正确 var canonicalizedResource = $"/{accountName}/{containerName}\ncomp:list\nprefix:contacts/{contactId}\nrestype:container"; // 修复:按顺序拼接规范请求头,Date字段留空 var canonicalizedHeaders = $"x-ms-date:{requestDate}\nx-ms-version:2023-08-03"; var stringToSign = $"GET\n\n\n\n\n\n\n\n\n\n\n\n{canonicalizedHeaders}\n{canonicalizedResource}"; string signature; using (var hmac = new HMACSHA256(Convert.FromBase64String(accessKey))) { var dataToHmac = Encoding.UTF8.GetBytes(stringToSign); signature = Convert.ToBase64String(hmac.ComputeHash(dataToHmac)); } // Make the HTTP GET request var url = $"https://{accountName}.blob.core.windows.net/{containerName}?restype=container&comp=list&prefix=contacts/{contactId}"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("x-ms-version", "2023-08-03"); client.DefaultRequestHeaders.Add("x-ms-date", requestDate); client.DefaultRequestHeaders.Add("Authorization", $"SharedKey {accountName}:{signature}"); var response = await client.GetAsync(url); // Process the response if (response.IsSuccessStatusCode) { var responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine("List of blobs in the container:"); Console.WriteLine(responseContent); } else { Console.WriteLine($"Error getting list of blobs. Status code: {response.StatusCode}"); } }
内容的提问来源于stack exchange,提问作者Johan Pino
相关产品推荐
相关产品推荐

