组合两个函数以生成令牌并读取二进制文件内容

huangapple go评论65阅读模式
英文:

Combining two functions to generate token and read blob file content

问题

[FunctionName("SasTokenFunction")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req)
{
    string connectionString = Environment.GetEnvironmentVariable("AzureStorage");
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
    CloudBlobClient client = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = client.GetContainerReference("formsample");

    SharedAccessBlobPolicy accessPolicy = new SharedAccessBlobPolicy
    {
        SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(30),
        Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read
    };

    string sasUriToken = $"{container.Uri}{container.GetSharedAccessSignature(accessPolicy)}";

    // Get the SAS Token with content and return it to the client app
    string sasTokenWithContent = GetUserDelegationSasBlobwithcontent();
    return (ActionResult)new OkObjectResult(sasUriToken + sasTokenWithContent);
}

public static string GetUserDelegationSasBlobwithcontent()
{
    string storageAccountUriString = "https://formsample5.blob.core.windows.net";
    var credential = new DefaultAzureCredential();

    BlobServiceClient blobServiceClient = new BlobServiceClient(new Uri(storageAccountUriString), credential);
    UserDelegationKey userDelegationKey = blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(1));
    BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient("sample"); //container name
    BlobClient blobClient = blobContainerClient.GetBlobClient("Sample.docx");

    // 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;
    string contentString = string.Empty;

    using (var streamReader = new StreamReader(content))
    {
        while (!streamReader.EndOfStream)
        {
            string line = streamReader.ReadLineAsync().Result;
            contentString += $"\nBlob-contents:{line}";
        }
    }

    return contentString;
}
英文:

I'm new to c#, as I'm working on developing Azure function to generate SAS token, and reading and modifying .docx blob file.

I have these two functions below to do the 2 tasks. However, I want to integrate them into one function. I've tried to do so, but there's something missing I couldn't understand.

[FunctionName(&quot;SasTokenFunction&quot;)]
public static async Task&lt;IActionResult&gt; Run([HttpTrigger(AuthorizationLevel.Function, &quot;get&quot;, Route = null)] HttpRequest req)
{

	string connectionString = Environment.GetEnvironmentVariable(&quot;AzureStorage&quot;);
	CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
	CloudBlobClient client = storageAccount.CreateCloudBlobClient();
	CloudBlobContainer container = client.GetContainerReference(&quot;formsample&quot;);

	SharedAccessBlobPolicy accessPolicy = new SharedAccessBlobPolicy
	{
		SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(30),
		Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read
	};

	string sasUriToken = $&quot;{container.Uri}{container.GetSharedAccessSignature(accessPolicy)}&quot;;

	// return the SAS Token to the client app
	GetUserDelegationSasBlobwithcontent();
	return (ActionResult)new OkObjectResult(sasUriToken);

}

public static async void GetUserDelegationSasBlobwithcontent()
{

	string storageAccountUriString = $&quot;https://formsample5.blob.core.windows.net&quot;;
	var credential = new DefaultAzureCredential();

	BlobServiceClient blobServiceClient = new BlobServiceClient(new Uri(storageAccountUriString), credential);
	UserDelegationKey userDelegationKey = blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(1));
	BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient(&quot;sample&quot;);  //container name
	BlobClient blobClient = blobContainerClient.GetBlobClient(&quot;Sample.docx&quot;);


	// Get a user delegation key 
	var sasBuilder = new BlobSasBuilder()
	{
		BlobContainerName = blobClient.BlobContainerName,
		BlobName = blobClient.Name,
		Resource = &quot;b&quot;, // 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(&quot;SAS-Token {0}&quot;, sasToken);

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

答案1

得分: 1

感谢Peter Csala的评论。

要将这两个功能结合在一起,您需要修改GetUserDelegationSasBlobwithcontent()函数的返回类型,使其返回blob文件的内容作为字符串或字节数组。然后,您可以在Run()函数内调用此函数,并将SAS令牌作为参数传递给GetUserDelegationSasBlobwithcontent()函数。

要将这两个功能整合在一起,您可以修改GetUserDelegationSasBlobwithcontent函数以返回blob文件的内容。然后,您可以在SasTokenFunction中调用此函数,并将结果返回给客户端应用程序。

以下是需要在代码中使用的命名空间:

using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage;
using Azure.Storage.Blobs;
using Azure.Identity;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Sas;

我使用了这段代码,并成功获取了令牌。

public static class Function1
{
    [FunctionName("SasTokenFunction")]
    public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req)
    {
        string connectionString = Environment.GetEnvironmentVariable("AzureStorage");
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
        CloudBlobClient client = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = client.GetContainerReference("samplecontainer");

        SharedAccessBlobPolicy accessPolicy = new SharedAccessBlobPolicy
        {
            SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(30),
            Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read
        };

        string sasUriToken = $"{container.Uri}{container.GetSharedAccessSignature(accessPolicy)}";

        string blobContent = await GetUserDelegationSasBlobwithcontent(sasUriToken);

        return (ActionResult)new OkObjectResult(sasUriToken);
    }

    public static async Task<string> GetUserDelegationSasBlobwithcontent(string sasToken)
    {
        string storageAccountUriString = "https://formsample5.blob.core.windows.net";
        var credential = new DefaultAzureCredential();

        BlobServiceClient blobServiceClient = new BlobServiceClient(new Uri(storageAccountUriString), credential);
        UserDelegationKey userDelegationKey = blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(1));
        BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient("sample");  //container name
        BlobClient blobClient = blobContainerClient.GetBlobClient("Sample.docx");

        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))
        {
            string blobContent = await streamReader.ReadToEndAsync();
            return blobContent;
        }
    }
}

令牌生成

组合两个函数以生成令牌并读取二进制文件内容

组合两个函数以生成令牌并读取二进制文件内容

获取SAS令牌的示例代码:

const string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=<storage-account>;AccountKey=<account-key>";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);
SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy()
{
    Permissions = SharedAccessAccountPermissions.Read |
                  SharedAccessAccountPermissions.Write |
                  SharedAccessAccountPermissions.List,
    Services = SharedAccessAccountServices.Blob | SharedAccessAccountServices.File,
    ResourceTypes = SharedAccessAccountResourceTypes.Service,
    SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
    Protocols = SharedAccessProtocol.HttpsOnly
};

return storageAccount.GetSharedAccessSignature(policy);

要了解更多信息,请参考MSDoc

英文:

Thanks to Peter Csala for the comments.
>To combine the two functions, you need to modify the return type of the GetUserDelegationSasBlobwithcontent() function to return the content of the blob file as a string or byte array. Then you can call this function inside the Run() function and pass the SAS token as a parameter to the GetUserDelegationSasBlobwithcontent() function.

To integrate the two functions into one, you can modify the GetUserDelegationSasBlobwithcontent function to return the contents of the blob file.
And you can call this function in the SasTokenFunction and return the result to the client app.

 string blobContent = await GetUserDelegationSasBlobwithcontent(sasUriToken);
 public static async Task&lt;string&gt; GetUserDelegationSasBlobwithcontent(string sasToken)
 {
 .
 .
 }

The below namespaces need to be used in the code.

using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage;
using Azure.Storage.Blobs;
using Azure.Identity;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Sas;

I used the code and able to fetch the token.

public static class Function1
    {
        [FunctionName(&quot;SasTokenFunction&quot;)]
        public static async Task&lt;IActionResult&gt; Run([HttpTrigger(AuthorizationLevel.Function, &quot;get&quot;, Route = null)] HttpRequest req)
        {

            string connectionString = Environment.GetEnvironmentVariable(&quot;AzureStorage&quot;);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
            CloudBlobClient client = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = client.GetContainerReference(&quot;samplecontainer&quot;);

            SharedAccessBlobPolicy accessPolicy = new SharedAccessBlobPolicy
            {
                SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(30),
                Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read
            };

            string sasUriToken = $&quot;{container.Uri}{container.GetSharedAccessSignature(accessPolicy)}&quot;;

            string blobContent = await GetUserDelegationSasBlobwithcontent(sasUriToken);


            return (ActionResult)new OkObjectResult(sasUriToken);
        }

        public static async Task&lt;string&gt; GetUserDelegationSasBlobwithcontent(string sasToken)
        {
            string storageAccountUriString = $&quot;https://formsample5.blob.core.windows.net&quot;;
            var credential = new DefaultAzureCredential();

            BlobServiceClient blobServiceClient = new BlobServiceClient(new Uri(storageAccountUriString), credential);
            UserDelegationKey userDelegationKey = blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(1));
            BlobContainerClient blobContainerClient = blobServiceClient.GetBlobContainerClient(&quot;sample&quot;);  //container name
            BlobClient blobClient = blobContainerClient.GetBlobClient(&quot;Sample.docx&quot;);

            Uri blobUri = new Uri(blobClient.Uri + &quot;?&quot; + sasToken);
            BlobClient sasBlobClient = new BlobClient(blobUri);
            BlobDownloadInfo download = sasBlobClient.Download();
            var content = download.Content;

            using (var streamReader = new StreamReader(content))
            {
                string blobContent = await streamReader.ReadToEndAsync();
                return blobContent;
            }
        }
    }

Token generation

组合两个函数以生成令牌并读取二进制文件内容

组合两个函数以生成令牌并读取二进制文件内容

Sample code to fetch the SAS token.

const string ConnectionString = &quot;DefaultEndpointsProtocol=https;AccountName=&lt;storage-account&gt;;AccountKey=&lt;account-key&gt;&quot;;
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);
            SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy()
            {
                Permissions = SharedAccessAccountPermissions.Read |
                                  SharedAccessAccountPermissions.Write |
                                  SharedAccessAccountPermissions.List,
                Services = SharedAccessAccountServices.Blob | SharedAccessAccountServices.File,
                ResourceTypes = SharedAccessAccountResourceTypes.Service,
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
                Protocols = SharedAccessProtocol.HttpsOnly
            };

            return storageAccount.GetSharedAccessSignature(policy);

For further information on this, refer to MSDoc.

huangapple
  • 本文由 发表于 2023年3月9日 21:31:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685300.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定