生成用于 Azure Blob 存储项的 SAS 访问令牌

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

Generating SAS access token for Azure Blob storage item

问题

我是完全新手使用Azure,我想生成SAS访问令牌以访问Blob项(Word文件),包括读取和写入此文件。

我的情景是:用户应该提交他们的数据,然后我应该接收这些数据作为字符串数组并将其放入存储在Azure Blob存储中的一个表单中。

我已经实现了将更新表单与用户数据的方法,因为我有一段代码来生成访问令牌,以及另一段用于读取和写入文件的代码,但对我来说它不起作用!

这是我的代码:

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

    // 获取用户委派密钥
    Azure.Storage.Blobs.Models.UserDelegationKey userDelegationKey =
        await blobServiceClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow,
                                                          DateTimeOffset.UtcNow.AddDays(7));

    // 创建SAS令牌
    BlobSasBuilder sasBuilder = new BlobSasBuilder()
    {
        BlobContainerName = blobClient.BlobContainerName,
        BlobName = blobClient.Name,
        Resource = "b",
        StartsOn = DateTimeOffset.UtcNow,
        ExpiresOn = DateTimeOffset.UtcNow.AddDays(7)
    };

    // 为SAS指定读取和写入权限。
    sasBuilder.SetPermissions(BlobSasPermissions.Read | BlobSasPermissions.Write);

    // 将SAS令牌添加到Blob URI。
    BlobUriBuilder blobUriBuilder = new BlobUriBuilder(blobClient.Uri)
    {
        // 指定用户委派密钥。
        Sas = sasBuilder.ToSasQueryParameters(userDelegationKey,
                                              blobServiceClient.AccountName)
    };

    Console.WriteLine("Blob用户委派SAS URI: {0}", blobUriBuilder);
    Console.WriteLine();
    return blobUriBuilder.ToUri();
}

static async Task ReadBlobWithSasAsync(Uri sasUri)
{
    // 读取文件内容
    public static void Run(Stream myBlob, string fileContent)
    {
        StreamReader contentReader = new StreamReader(myBlob);
        string sampleContent = contentReader.ReadToEnd();
        char[] separator = { ' ' };
        string[] content = sampleContent.Split(separator);
        reader.FillForm(content);
    }

    // 创建用于Blob操作的BlobClient对象。
    BlobClient blobClient = new BlobClient(sasUri, null);

    // 下载并读取Blob的内容。
    try
    {
        Console.WriteLine("Blob内容:");

        // 将Blob内容下载到流中并读取流。
        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("SAS {0} 的读取操作成功", sasUri);
        Console.WriteLine();
    }
    catch (RequestFailedException e)
    {
        // 检查是否出现403(禁止)错误。如果SAS无效,Azure存储将返回此错误。
        if (e.Status == 403)
        {
            Console.WriteLine("SAS {0} 的读取操作失败", sasUri);
            Console.WriteLine("附加错误信息:" + e.Message);
            Console.WriteLine();
        }
        else
        {
            Console.WriteLine(e.Message);
            Console.ReadLine();
            throw;
        }
    }
}

希望这有所帮助。如果你有任何问题或需要进一步的帮助,请随时提出。

英文:

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&lt;Uri&gt; 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 = &quot;b&quot;,
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(&quot;Blob user delegation SAS URI: {0}&quot;, 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 = { &#39; &#39; };
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(&quot;Blob contents:&quot;);
// 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(&quot;Read operation succeeded for SAS {0}&quot;, 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(&quot;Read operation failed for SAS {0}&quot;, sasUri);
Console.WriteLine(&quot;Additional error information: &quot; + e.Message);
Console.WriteLine();
}
else
{
Console.WriteLine(e.Message);
Console.ReadLine();
throw;
}
}
}

答案1

得分: 0

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

> 我想生成一个SAS访问令牌,用于访问一个包括读写的Blob项目(Word文件)。

您可以使用以下代码生成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");

            // 获取用户委派密钥
            var sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = blobClient.BlobContainerName,
                BlobName = blobClient.Name,
                Resource = "b", // b代表Blob,c代表Container
                StartsOn = DateTimeOffset.UtcNow,
                ExpiresOn = DateTimeOffset.UtcNow.AddHours(4),
            };
            sasBuilder.SetPermissions(BlobSasPermissions.Read | BlobSasPermissions.Write); // 读取权限

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

输出:

生成用于 Azure Blob 存储项的 SAS 访问令牌

参考:
使用.NET创建用户委派SAS以访问容器、目录或Blob - Azure存储 | 微软学习

英文:

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 = $&quot;https://storage13261.blob.core.windows.net&quot;;
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(&quot;test&quot;);  //container name
var blobClient = blobContainerClient.GetBlobClient(&quot;address.txt&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)
{
var line = await streamReader.ReadLineAsync();
Console.WriteLine(&quot;\nBlob-contents:{0}&quot;,line);
}
}
}
public static void Main()
{
GetUserDelegationSasBlobwithcontent();
}
}
}

Output:

生成用于 Azure Blob 存储项的 SAS 访问令牌

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

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

发表评论

匿名网友

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

确定