在Azure存储上,CanGenerateSasUri始终为false
c#
我有一个使用 Azure 存储的 ASP .Net Core 3.1 Web API。为此,它使用了 Microsoft.Azure.Storage.Blob 库。NuGet 包管理器通知我该包已被弃用,我应该使用 Azure.Storage.Blobs。我这样做了,并继续修复由于此更改而导致的所有损坏代码。在我找到为客户端生成共享访问签名 (SAS) 的代码之前,我没有遇到很多问题。无论如何,我设法通过以下代码使其工作:
https://docs.microsoft.com/en-us/azure/storage/blobs/sas-service-create?tabs=dotnet
private static Uri GetServiceSasUriForContainer(BlobContainerClient containerClient,
string storedPolicyName = null)
{
// Check whether this BlobContainerClient object has been authorized with Shared Key.
if (containerClient.CanGenerateSasUri)
{
// Create a SAS token that's valid for one hour.
BlobSasBuilder sasBuilder = new BlobSasBuilder()
{
BlobContainerName = containerClient.Name,
Resource = "c"
};
if (storedPolicyName == null)
{
sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
sasBuilder.SetPermissions(BlobContainerSasPermissions.Read);
}
else
{
sasBuilder.Identifier = storedPolicyName;
}
Uri sasUri = containerClient.GenerateSasUri(sasBuilder);
Console.WriteLine("SAS URI for blob container is: {0}", sasUri);
Console.WriteLine();
return sasUri;
}
else
{
Console.WriteLine(@"BlobContainerClient must be authorized with Shared Key
credentials to create a service SAS.");
return null;
}
}
但是,该行Uri sasUri = containerClient.GenerateSasUri(sasBuilder);
给了我一个错误,经过进一步研究,我改为使用:
StorageSharedKeyCredential credential = new StorageSharedKeyCredential(storageAccountName, storageAccountKey);
但是,我也不得不注释掉该行,if (containerClient.CanGenerateSasUri)
因为它总是错误的。显然这是因为“必须使用共享密钥凭据授权 BlobContainerClient 才能创建服务 SAS。” 但据我所知,我使用的是共享密钥凭据。我没有使用 Azure AD 身份验证(即使我知道这是推荐的方法)。我的 BlobServiceClient 正在像这样初始化:
string storageConnectionString = $"DefaultEndpointsProtocol=https;AccountName=propworx;AccountKey={storageAccountKey};EndpointSuffix=core.windows.net";
BlobServiceClient blobServiceClient = new BlobServiceClient(storageConnectionString);
有谁知道为什么 CanGenerateSasUri 是假的?
回答
“必须使用共享密钥凭据授权 BlobContainerClient 才能创建服务 SAS。” 意味着您应该直接构建BlobContainerClient
而不是BlobServiceClient
使用凭据,然后将其传递给GetServiceSasUriForContainer
方法。
例如,使用下面的代码:
var storageAccountName = "xxx";
var storageAccountKey = "xxx";
var container_name = "xxx";
StorageSharedKeyCredential credential = new StorageSharedKeyCredential(storageAccountName, storageAccountKey);
//build the blob container url
string blobcontainer_url = string.Format("https://{0}.blob.core.windows.net/{1}", storageAccountName, container_name);
//directly build BlobContainerClient, then pass it to GetServiceSasUriForContainer() method
BlobContainerClient blobContainer = new BlobContainerClient(new Uri(blobcontainer_url), credential);
Uri mysasuri = GetServiceSasUriForContainer(blobContainer, null);
测试结果: