Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

Azure Storage: How to generate a SAS connection string using .NET SDK

I'm currently generating SAS tokens using the Microsoft.WindowsAzure.Storage.CloudStorageAccount class like so:

var cloudStorageAccount = // create a new CloudStorageAccount
var sharedAccessAccountPolicy = new SharedAccessAccountPolicy
{
    Permissions = SharedAccessAccountPermissions.Read | SharedAccessAccountPermissions.Write,
    Services = SharedAccessAccountServices.Blob,
    ResourceTypes = SharedAccessAccountResourceTypes.Object,
    SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1),
    Protocols = SharedAccessProtocol.HttpsOnly
};

var token = cloudStorageAccount.GetSharedAccessSignature(sharedAccessAccountPolicy);

However, this returns a token with a ? in front and does not include the blob endpoint. I was looking at this documentation and noticed a SAS looks like below:

BlobEndpoint=https://storagesample.blob.core.windows.net;
SharedAccessSignature=sv=2015-04-05&sr=b&si=tutorial-policy-635959936145100803&sig=9aCzs76n0E7y5BpEi2GvsSv433BZa22leDOZXX%2BXXIU%3D

What's neat about this is that I can use it as a connection string to directly initialize a BlockBlobClient.

How can I generate my token in the above format? I can parse my own and remove the ? and then add the BlobEndpoint and SharedAccessSignature keys, but this is manual work and may not function properly in the future. Is there an SDK method that creates a SAS in the format that's shown on Microsoft's documentation?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I believe you are using WindowsAzure.Storage library. This library is deprecated.

https://www.nuget.org/packages/WindowsAzure.Storage/

The recommended library to use is https://www.nuget.org/packages/Azure.Storage.Blobs (v12)

With the v12 library, I was able to get a SASUri for a particular blob and create a BlobClient using the SASUri to download that blob without a need for string formatting.

 BlobClient blobClient = new BlobClient("storage account conn string", "container name", "blob name");
        BlobSasBuilder blobSasBuilder = new BlobSasBuilder(BlobSasPermissions.Write | BlobSasPermissions.Read, DateTimeOffset.Now.AddDays(1))
        {
            BlobContainerName = blobClient.BlobContainerName,
            BlobName = blobClient.Name
        };

        var sasuri = blobClient.GenerateSasUri(blobSasBuilder);

        var blobClientWithSasUri = new BlobClient(sasuri);
        using (var fileStream = System.IO.File.OpenWrite(@"path to download"))
        {
            blobClientWithSasUri.DownloadTo(fileStream);
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...