如何在C#中使用SAS访问Azure Blob [英] How to access Azure blob using SAS in C#

查看:261
本文介绍了如何在C#中使用SAS访问Azure Blob的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用临时共享访问签名(SAS)创建/访问Azure Blob时,我收到远程服务器返回错误:(403)禁止访问".错误.有人可以帮助我确定此代码出了什么问题.

When I am trying to create / access Azure blob using Ad-hoc Shared Access Signature (SAS) I am getting "The remote server returned an error: (403) Forbidden." error. Can someone help me to identify, what is going wrong with this code.

    // Calling this function from Main().
    public void uploadToBlob()
    {
        string content = "Hello World - Content of the file";
        string fileName = "TestFile";
        UploadFileToAzureBlobStorage(content, fileName);
    }

    void UploadFileToAzureBlobStorage(string content, string fileName)
    {
        string storageKey = "SAS Key";
        string storageAccount = "Storage Account name";
        string containerName = "Container Name";
        string blobName = fileName;

        string method = "PUT";
        string sampleContent = content;
        int contentLength = Encoding.UTF8.GetByteCount(sampleContent);

        string requestUri = $"https://{storageAccount}.blob.core.windows.net/{containerName}/{blobName}";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
        string now = DateTime.UtcNow.ToString("R");
        request.Method = method;
        request.ContentType = "text/plain; charset=UTF-8";
        request.ContentLength = contentLength;
        request.Headers.Add("x-ms-version", "2015-12-11");
        request.Headers.Add("x-ms-date", now);
        request.Headers.Add("x-ms-blob-type", "BlockBlob");
        request.Headers.Add("Authorization", AuthorizationHeader(method, now, request, storageAccount, storageKey, containerName, blobName));

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(Encoding.UTF8.GetBytes(sampleContent), 0, contentLength);
        }

        using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
        {
            if (resp.StatusCode == HttpStatusCode.OK)
            { }
        }
    }

    public string AuthorizationHeader(string method, string now, HttpWebRequest request, string storageAccount, string storageKey, string containerName, string blobName)
    {
        string headerResource = $"x-ms-blob-type:BlockBlob\nx-ms-date:{now}\nx-ms-version:2015-12-11";
        string urlResource = $"/{storageAccount}/{containerName}/{blobName}";
        string stringToSign = $"{method}\n\n\n{request.ContentLength}\n\n{request.ContentType}\n\n\n\n\n\n\n{headerResource}\n{urlResource}";
        HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(storageKey));
        string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
        String AuthorizationHeader = String.Format("{0} {1}:{2}", "SharedKey", storageAccount, signature);
        return AuthorizationHeader;
    }

推荐答案

使用帐户密钥时,需要上面使用的代码.这是您需要计算并在请求中包含Authorization标头的时候.如果您使用的是Shared Access Signature (SAS)令牌,则无需执行所有操作,因为SAS令牌已包含授权信息.

The code you're using above is needed when you're using an account key. This is when you would need to compute and include Authorization header in your request. If you're using a Shared Access Signature (SAS) token, you don't need to do all of this because SAS token already includes authorization information.

假设您的SAS令牌有效并且包含上传文件的适当权限,您的代码将变得非常简单.请在下面查看修改后的代码:

Assuming your SAS Token is valid and contain appropriate permissions to upload a file, your code becomes quite simple. Please see modified code below:

void UploadFileToAzureBlobStorage(string content, string fileName)
{
    string sasToken = "SAS Key";
    string storageAccount = "Storage Account name";
    string containerName = "Container Name";
    string blobName = fileName;

    string method = "PUT";
    string sampleContent = content;
    int contentLength = Encoding.UTF8.GetByteCount(sampleContent);

    string requestUri = $"https://{storageAccount}.blob.core.windows.net/{containerName}/{blobName}?{sasToken}";

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
    request.Method = method;
    request.ContentType = "text/plain; charset=UTF-8";
    request.ContentLength = contentLength;
    request.Headers.Add("x-ms-blob-type", "BlockBlob");

    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(Encoding.UTF8.GetBytes(sampleContent), 0, contentLength);
    }

    using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
    {
        if (resp.StatusCode == HttpStatusCode.OK)
        { }
    }
}

这篇关于如何在C#中使用SAS访问Azure Blob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆