Visual Studio 正在为Azure Blob存储项生成SAS访问令牌

ykejflvf  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(138)

我是Azure的新手,我想为blob项(word文件)生成SAS访问令牌,包括阅读和写入此文件。
我的设想是:用户应该提交他们的数据,然后我应该接收这个数据作为一个字符串数组,并把它放入一个存储在Azure blob存储中的形式。
我已经实现了用用户数据更新表单的方法,因为我有一段代码来生成访问令牌,还有一段代码来读写文件,但是这对我来说不起作用!
这是我的代码:

async static Task<Uri> GetUserDelegationSasBlob(BlobClient blobClient)
        {
            BlobServiceClient blobServiceClient =
                blobClient.GetParentBlobContainerClient().GetParentBlobServiceClient();

            // Get a user delegation key 
            Azure.Storage.Blobs.Models.UserDelegationKey userDelegationKey =
                await blobServiceClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow,
                                                                  DateTimeOffset.UtcNow.AddDays(7));

            // Create a SAS token
            BlobSasBuilder sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = blobClient.BlobContainerName,
                BlobName = blobClient.Name,
                Resource = "b",
                StartsOn = DateTimeOffset.UtcNow,
                ExpiresOn = DateTimeOffset.UtcNow.AddDays(7)
            };

            // Specify read and write permissions for the SAS.
            sasBuilder.SetPermissions(BlobSasPermissions.Read | BlobSasPermissions.Write);

            // Add the SAS token to the blob URI.
            BlobUriBuilder blobUriBuilder = new BlobUriBuilder(blobClient.Uri)
            {
                // Specify the user delegation key.
                Sas = sasBuilder.ToSasQueryParameters(userDelegationKey,
                                                      blobServiceClient.AccountName)
            };

            Console.WriteLine("Blob user delegation SAS URI: {0}", blobUriBuilder);
            Console.WriteLine();
            return blobUriBuilder.ToUri();
        }


        static async Task ReadBlobWithSasAsync(Uri sasUri)
        {

         //Read file content
        public static void Run(Stream myBlob, string fileContent)
        {
            StreamReader contentReader = new StreamReader(myBlob);
            string sampleContent = contentReader.ReadToEnd();
            char[] spearator = { ' ' };
            string[] content = sampleContent.Split(spearator);
            reader.FillForm(content);

        }

            // Create a blob client object for blob operations.
            BlobClient blobClient = new BlobClient(sasUri, null);

            // Download and read the contents of the blob.
            try
            {
                Console.WriteLine("Blob contents:");

                // Download blob contents to a stream and read the stream.
                BlobDownloadInfo blobDownloadInfo = await blobClient.DownloadAsync();
                using (StreamReader reader = new StreamReader(blobDownloadInfo.Content, true))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }

                Console.WriteLine();
                Console.WriteLine("Read operation succeeded for SAS {0}", sasUri);
                Console.WriteLine();
            }
            catch (RequestFailedException e)
            {
                // Check for a 403 (Forbidden) error. If the SAS is invalid, 
                // Azure Storage returns this error.
                if (e.Status == 403)
                {
                    Console.WriteLine("Read operation failed for SAS {0}", sasUri);
                    Console.WriteLine("Additional error information: " + e.Message);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                    throw;
                }
            }
        }
zfycwa2u

zfycwa2u1#

我在自己的环境中尝试,得到了以下结果:

我想为blob项(word文件)生成SAS访问令牌,包括阅读和写入此文件。
您可以使用以下代码生成SAS令牌并从azure blob存储读取内容:

代码:

using Azure;
using Azure.Identity;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;
using Azure.Storage.Sas;
using System.ComponentModel;

namespace SAStoken
{
    class Program
    {
        public static async void GetUserDelegationSasBlobwithcontent()
        {
            var storageAccountUriString = $"https://storage13261.blob.core.windows.net";
            var credential = new DefaultAzureCredential();

            var blobServiceClient = new BlobServiceClient(new Uri(storageAccountUriString), credential);

            var userDelegationKey = blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(1));

            var blobContainerClient = blobServiceClient.GetBlobContainerClient("test");  //container name
            var blobClient = blobContainerClient.GetBlobClient("address.txt");

            // Get a user delegation key 
            var sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = blobClient.BlobContainerName,
                BlobName = blobClient.Name,
                Resource = "b", // b for blob, c for container
                StartsOn = DateTimeOffset.UtcNow,
                ExpiresOn = DateTimeOffset.UtcNow.AddHours(4),
            };
            sasBuilder.SetPermissions(BlobSasPermissions.Read |BlobSasPermissions.Write); // read permissions

            string sasToken = sasBuilder.ToSasQueryParameters(userDelegationKey, blobServiceClient.AccountName).ToString();
            Console.WriteLine("SAS-Token {0}", sasToken) ;

            Uri blobUri = new Uri(blobClient.Uri + "?" + sasToken);
            BlobClient sasBlobClient = new BlobClient(blobUri);
            BlobDownloadInfo download = sasBlobClient.Download();
            var content = download.Content;
            using (var streamReader = new StreamReader(content))
            {
                while (!streamReader.EndOfStream)
                {
                    var line = await streamReader.ReadLineAsync();
                    Console.WriteLine("\nBlob-contents:{0}",line);
                }
            }
        }

        
        public static void Main()
        {
            GetUserDelegationSasBlobwithcontent();
        }

    }
}

输出:

参考:Use .NET to create a user delegation SAS for a container, directory, or blob - Azure Storage | Microsoft Learn

相关问题