gpt4 book ai didi

C# 如何使用服务 SAS 授权客户端对象

转载 作者:行者123 更新时间:2023-12-03 06:14:57 27 4
gpt4 key购买 nike

我正在创建 Blazor Webassemble 应用程序。我正在使用 Azurite 存储模拟器来模拟开发中的 Azure 存储,并且我已经安装了 Azure 存储资源管理器。

我正在关注Create a service SAS for a blob with .NET让我的应用程序连接到我的开发者存储帐户的示例。

在他们提供的示例代码中:

// Create a Uri object with a service SAS appended
BlobClient blobClient = blobServiceClientSharedKey
.GetBlobContainerClient("sample-container")
.GetBlobClient("sample-blob.txt");
Uri blobSASURI = await CreateServiceSASBlob(blobClient);

// Create a blob client object representing 'sample-blob.txt' with SAS authorization
BlobClient blobClientSAS = new BlobClient(blobSASURI);

我不确定 blobServiceClientSharedKey 是什么。

我有点知道共享 key 是什么,但我不知道他们希望我在这里用它做什么。如果我将他们的代码粘贴到 Visual Studio 中,它不会编译。 Visual Studio 不知道 blobServiceClientSharedKey 是什么。

有人可以给我指出正确的方向吗?

更新:已解决

嗯,我让它工作了,但我认为它没有正确利用存储访问策略。但我想发布我的代码,它允许我创建一个 blob,而无需将容器设置为允许匿名访问。我认为它至少在某种程度上是安全的。

public class StorageService
{
private readonly IConfiguration configuration;

public StorageService(IConfiguration Configuration)
{
configuration = Configuration;
}
public StorageSharedKeyCredential GetStorageSharedKeyCredential()
{
string? accountName = configuration["BlobStorage:Name"] ?? "";
string? accountKey = configuration["BlobStorage:AccountKey"] ?? "";
StorageSharedKeyCredential storageSharedKeyCredential =
new(accountName, accountKey);

return storageSharedKeyCredential;
}

public async Task<BlobContainerClient> CreateBlobClient()
{
// Create a BlobServiceClient object with the account SAS appended
string? blobServiceURI = configuration["BlobStorage:Url"];
string sasToken = await CreateAccountSAS(GetStorageSharedKeyCredential());
BlobServiceClient blobServiceClientAccountSAS = new BlobServiceClient(new Uri($"{blobServiceURI}?{sasToken}"));

BlobContainerClient blobContainerClient = blobServiceClientAccountSAS.GetBlobContainerClient(configuration["BlobStorage:ContainerName"]);

blobContainerClient = await CreateStoredAccessPolicyAsync(blobContainerClient);
return blobContainerClient;
}


public async Task<string> CreateAccountSAS(StorageSharedKeyCredential sharedKey)
{
// Create a SAS token that's valid for one day
AccountSasBuilder sasBuilder = new AccountSasBuilder()
{
Services = AccountSasServices.All,
ResourceTypes = AccountSasResourceTypes.All,
ExpiresOn = DateTimeOffset.UtcNow.AddDays(1),
Protocol = SasProtocol.HttpsAndHttp
};

sasBuilder.SetPermissions(AccountSasPermissions.All);

// Use the key to get the SAS token
string sasToken = sasBuilder.ToSasQueryParameters(sharedKey).ToString();

return sasToken;
}

public async Task<BlobContainerClient> CreateStoredAccessPolicyAsync(BlobContainerClient containerClient)
{
// Create a stored access policy with read and write permissions, valid for one day
List<BlobSignedIdentifier> signedIdentifiers = new List<BlobSignedIdentifier>
{
new BlobSignedIdentifier
{
Id = "sample-read-write-policy",
AccessPolicy = new BlobAccessPolicy
{
StartsOn = DateTimeOffset.UtcNow,
ExpiresOn = DateTimeOffset.UtcNow.AddDays(1),
Permissions = "rw"
}
},
new BlobSignedIdentifier
{
Id = "sample-read-policy",
AccessPolicy = new BlobAccessPolicy
{
StartsOn = DateTimeOffset.UtcNow,
ExpiresOn = DateTimeOffset.UtcNow.AddDays(1),
Permissions = "r"
}
}
};
// Set the container's access policy
await containerClient.SetAccessPolicyAsync(permissions: signedIdentifiers);

return containerClient;
}

public async Task<string> UploadAsync(string base64, string userId)
{
var encodedImage = base64.Split(',')[1];
var decodedImage = Convert.FromBase64String(encodedImage);

try
{
BlobContainerClient container = await CreateBlobClient();

if (await container.ExistsAsync() == false)
{
await container.CreateIfNotExistsAsync();
}

using (var fileStream = new MemoryStream(decodedImage))
{
BlobClient blobClient = container.GetBlobClient($"{userId}.png");

// upload image stream to blob
await blobClient.UploadAsync(fileStream, true);
return $"{userId}.png";
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return string.Empty;
}
}

应用程序设置

"BlobStorage": {
"ConnectionString": "UseDevelopmentStorage=true",
"Url": "http://127.0.0.1:10000/devstoreaccount1",
"ContainerName": "profile-pics",
"Name": "devstoreaccount1",
"AccountKey": "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="
}

enter image description here

最佳答案

即使我不确定为什么官方文档会提到这一点。但是,“blobServiceClientSharedKey”应该是一个“BlobServiceClient”对象,它被注入(inject)到构造函数中。

BlobClient blobClient = blobServiceClient
.GetBlobContainerClient("sample-container")
.GetBlobClient("sample-blob.txt");
Uri blobSASURI = await CreateServiceSASBlob(blobClient);

// Create a blob client object representing 'sample-blob.txt' with SAS authorization
BlobClient blobClientSAS = new BlobClient(blobSASURI);

BlobServiceClient

确保在 Program.cs 文件中添加服务。

关于C# 如何使用服务 SAS 授权客户端对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76345179/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com