我正在尝试使用azure存储中的rest api创建容器。我已经按照Microsoft提供的here文档中的所有内容进行了操作,并尝试从here创建授权令牌。我还是得到了:
403 Forbidden Server无法验证请求。确保 正确形成Authorization标头的值,包括 签名。
以下是我的代码段。
class Program
{
private const string BlobStorageAccount = "myacc";
private const string BlobStorageAccessKey = "ACCESS_KEY";
static void Main(string[] args)
{
CreateContainer("myfirstcontainer");
}
private static bool CreateContainer(string containerName)
{
String requestMethod = "PUT";
String msVersion = "2016-05-31";
string dt = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
String canHeaders = String.Format("x-ms-date:{0}\nx-ms-version:{1}", dt, msVersion);
String canResource = String.Format("/{0}/{1}\nrestype:container", BlobStorageAccount, containerName);
String SignStr = String.Format("{0}\n\n\n\n\n\n\n\n\n\n\n\n{1}\n{2}", requestMethod, canHeaders, canResource);
string auth = CreateAuthString(SignStr);
string urlPath = string.Format("https://{0}.blob.core.windows.net/{1}?restype=container", BlobStorageAccount, containerName);
Uri uri = new Uri(urlPath);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("x-ms-date", dt);
client.DefaultRequestHeaders.Add("x-ms-version", "2016-05-31");
client.DefaultRequestHeaders.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
client.DefaultRequestHeaders.Add("Authorization", auth);
HttpContent empty = null;
HttpResponseMessage response = client.PutAsync(uri, empty).Result;
return response.IsSuccessStatusCode;
}
private static String CreateAuthString(String SignStr)
{
String signature = string.Empty;
byte[] unicodeKey = Convert.FromBase64String(BlobStorageAccessKey);
using (HMACSHA256 hmacSha256 = new HMACSHA256(unicodeKey))
{
Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(SignStr);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
String authorizationHeader = String.Format(
CultureInfo.InvariantCulture,
"{0} {1}:{2}",
"SharedKey",
BlobStorageAccount,
signature);
return authorizationHeader;
}
}
答案 0 :(得分:2)
您的请求包含3个请求标头,但canHeaders
仅包含2.因此您需要在那里添加第3个标头。
var clientRequestId = Guid.NewGuid().ToString();
String canHeaders = String.Format("x-ms-client-request-id:{0}\nx-ms-date:{1}\nx-ms-version:{2}", clientRequestId, dt, msVersion);
String canResource = String.Format("/{0}/{1}\nrestype:container", BlobStorageAccount, containerName);
String SignStr = String.Format("{0}\n\n\n\n\n\n\n\n\n\n\n\n{1}\n{2}", requestMethod, canHeaders, canResource);
string auth = CreateAuthString(SignStr);
string urlPath = string.Format("https://{0}.blob.core.windows.net/{1}?restype=container", BlobStorageAccount, containerName);
Uri uri = new Uri(urlPath);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("x-ms-date", dt);
client.DefaultRequestHeaders.Add("x-ms-version", "2016-05-31");
client.DefaultRequestHeaders.Add("x-ms-client-request-id", clientRequestId);
client.DefaultRequestHeaders.Add("Authorization", auth);