0

I'm totally new to Azure, and I want to generate SAS access token for a blob item (word file) including reading and writing to this file.

My scenario is: a user should submit their data, then I should receive this data as a string array and put it into a form stored in an Azure blob storage.

I've already implemented the method that will update the form with the user data, as I've got a piece of code to generate the access token, and another one to read and write to the file, but it doesn't work for me!

This is my code:

 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;
                }
            }
        }

1 Answers1

0

I tried in my environment and got the below results:

I want to generate a SAS access token for a blob item (word file) including reading and writing to this file.

You can use the below code to generate a SAS token and read the content from the azure blob storage:

Code:

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();
        }

    }
}

Output:

enter image description here

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

Venkatesan
  • 3,748
  • 1
  • 3
  • 15
  • I tried this class but it's giving me " No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.)" How to change the defualt credentials please ? – Jeanpaul Mar 09 '23 at 08:16
  • Check this similar error https://stackoverflow.com/questions/47682760/no-job-functions-found-try-making-your-job-classes-and-methods-public – Venkatesan Mar 09 '23 at 08:24
  • Thanks for sharing this. I went through it but I couldn't get it clearly, I thought they were talking about different point! – Jeanpaul Mar 09 '23 at 09:41
  • I just want to know how to set DefaultAzureCredential value please? – Jeanpaul Mar 09 '23 at 10:33
  • Check this link explaining about defaultazurecredentials https://www.c-sharpcorner.com/article/defaultazureidentity-and-its-various-credential-types3/#:~:text=DefaultAzureCredential%201%20using%20System%3B%202%20using%20Azure.Identity%3B%203,8%20KeyVaultSecret%20secret%20%3D%20client.GetSecret%20%28secretKey%29%3B%20More%20items – Venkatesan Mar 09 '23 at 10:42
  • I've read it but the author didn't mention how to access and edit the system environment variables that will be used by the defaultazurecredentials class! – Jeanpaul Mar 09 '23 at 11:01