我正在使用Azure.Storage.Blobs v12.1.0
库。我正在使用带有Azure服务主体凭据的用户委派生成Blob级SAS令牌,并尝试使用生成的SAS令牌上传Blob。我已经完全按照Azure的this code示例生成了SAS令牌。
这是我用来创建SAS令牌的代码:
string blobEndpoint = string.Format("https://{0}.blob.core.windows.net", storageProviderSettings.AccountName);
TokenCredential credential =
new ClientSecretCredential(
storageProviderSettings.TenantId,
storageProviderSettings.ClientId,
storageProviderSettings.ClientSecret,
new TokenCredentialOptions());
BlobServiceClient blobServiceClient = new BlobServiceClient(new Uri(blobEndpoint),
credential);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
BlobClient blobClient = containerClient.GetBlobClient(blobName);
var delegationKey = await blobServiceClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(7));
BlobSasBuilder sasBuilder = new BlobSasBuilder()
{
BlobContainerName = containerName,
BlobName = blobName,
Resource = "b",
StartsOn = DateTimeOffset.UtcNow,
ExpiresOn = DateTimeOffset.UtcNow.AddSeconds(expirySeconds)
};
sasBuilder.SetPermissions(BlobSasPermissions.All);
// if (withDownloadAccess) {
// sasBuilder.SetPermissions(BlobSasPermissions.Read);
// }
// if (withDeleteAccess) {
// sasBuilder.SetPermissions(BlobSasPermissions.Delete);
// }
Console.WriteLine(sasBuilder.Permissions);
var sasQueryParams = sasBuilder.ToSasQueryParameters(delegationKey, storageProviderSettings.AccountName).ToString();
UriBuilder sasUri = new UriBuilder()
{
Scheme = "https",
Host = string.Format("{0}.blob.core.windows.net", storageProviderSettings.AccountName),
Path = string.Format("{0}/{1}", containerName, blobName),
Query = sasQueryParams
};
BlobServiceClient service = new BlobServiceClient(sasUri.Uri);
await service.GetPropertiesAsync();
Settings tmpUploadCredentials = CreateTemporaryAzureStorageProviderSettings(sasUri, storageProviderSettings);
Console.WriteLine(tmpUploadCredentials.ConnectionString);
return tmpUploadCredentials;
SAS令牌已创建,如果我将其保存在浏览器中,但Get Blob可以正常工作,但是如果我尝试上传文件或执行任何正在使用的操作,则使用BlobServiceClient
。要检查它是否已通过身份验证,我已经写了这行await service.GetPropertiesAsync();
,并抛出以下错误:
任何帮助将不胜感激。
service.GetPropertiesAsync();
是帐户上的一项操作。这意味着它将调用Get Blob Service Properties rest api以获取帐户的Blob服务的属性。但是,在创建BlobServiceClient
时,将提供Blob网址。 Blob不支持该操作。所以你会得到错误。它会想要获取Blob的属性,请调用api。因此,请按照以下代码更新您的代码
BlobClient blobClient = new BlobClient(sasUri, null);
blobClient.GetPropertiesAsync();
有关更多详细信息,请参阅https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blob-user-delegation-sas-create-dotnet#get-the-user-delegation-key