如何使用最新的 Azure SDK .NET API v12 在 Blob 上获取共享访问签名?

Kzr*_*tof 23 c# azure azure-storage-blobs azure-sas

我曾经能够使用 v11 Azure SDK API 在 Blob 上创建共享访问签名,如下所示:

var containerName = "mycontainer";
var blobName = "myblob";

CloudStorageAccount storageAccount 
 = CloudStorageAccount.Parse(<StorageConnectionString>);

CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

CloudBlobContainer container = blobClient.GetContainerReference(containerName);


SharedAccessBlobPermissions permission = SharedAccessBlobPermissions.Read;

TimeSpan clockSkew = TimeSpan.FromMinutes(15d);
TimeSpan accessDuration = TimeSpan.FromMinutes(15d);

var blobSAS = new SharedAccessBlobPolicy
{
    SharedAccessStartTime = DateTime.UtcNow.Subtract(clockSkew),
    SharedAccessExpiryTime = DateTime.UtcNow.Add(accessDuration) + clockSkew,
    Permissions = permissions
};

CloudBlockBlob blob = container.GetBlockBlobReference(blobName);

string sasBlobToken = blob.GetSharedAccessSignature(blobSAS);

...
Run Code Online (Sandbox Code Playgroud)

我想使用最新的 v12 .NET API,它似乎CloudBlobClientBlobServiceClientCloudBlobContainerBlobContainerClientCloudBlockBlobBlobClient.

但是,GetSharedAccessSignatureCloudBlockBlob实例上可用的方法在实例上不可用BlobClient

如何BlobClient使用最新的 Azure SDK .NET API v12从实例获取共享访问签名?

Kzr*_*tof 34

Sajeetharan 的回答让我寻找一个实际存在的BlobSasBuilder类。

这是我如何在服务器上构建一个:

//  Creates a client to the BlobService using the connection string.
var blobServiceClient = new BlobServiceClient(storageConnectionString);

//  Gets a reference to the container.
var blobContainerClient = blobServiceClient.GetBlobContainerClient(<ContainerName>);

//  Gets a reference to the blob in the container
BlobClient blobClient = containerClient.GetBlobClient(<BlobName>);

//  Defines the resource being accessed and for how long the access is allowed.
var blobSasBuilder = new BlobSasBuilder
{
    StartsOn = DateTime.UtcNow.Subtract(clockSkew), 
    ExpiresOn = DateTime.UtcNow.Add(accessDuration) + clockSkew,
    BlobContainerName = <ContainerName>,
    BlobName = <BlobName>,
};
    
//  Defines the type of permission.
blobSasBuilder.SetPermissions(BlobSasPermissions.Write);
       
//  Builds an instance of StorageSharedKeyCredential      
var storageSharedKeyCredential = new StorageSharedKeyCredential(<AccountName>, <AccountKey>);

//  Builds the Sas URI.
BlobSasQueryParameters sasQueryParameters = blobSasBuilder.ToSasQueryParameters(storageSharedKeyCredential);
Run Code Online (Sandbox Code Playgroud)

以下是在客户端使用它的方法:

//  Builds the URI to the blob storage.
UriBuilder fullUri = new UriBuilder()
{
    Scheme = "https",
    Host = string.Format("{0}.blob.core.windows.net", <AccountName>),
    Path = string.Format("{0}/{1}", <ContainerName>, <BlobName>),
    Query = sasQueryParameters.ToString()
};

//  Get an instance of BlobClient using the URI.
var blobClient = new BlobClient(fullUri.Uri, null);

//  Upload stuff in the blob.
await blobClient.UploadAsync(stream);
Run Code Online (Sandbox Code Playgroud)

附录

正如@one2012 在评论中所提到的,在这个答案展示了 Azure.Storage 命名空间中的所有功能几个月后已经建立了一个页面。该链接可用于获取更多信息。

  • @benjamin `var csBuilder = new DbConnectionStringBuilder(); csBuilder.ConnectionString = _configuration.GetConnectionString("MyCS"); var storageSharedKeyCredential = new StorageSharedKeyCredential( (string)csBuilder["AccountName"], (string)csBuilder["AccountKey"]);` (9认同)
  • 我找不到从连接字符串获取 storageSharedKeyCredential 的方法,而不是使用 AccountName 和 AccountKey。你知道有什么办法吗? (7认同)
  • 如果您要迁移到 Azure.Storage 命名空间,此页面是我发现的最有用的东西 https://www.craftedforeveryone.com/beginners-guide-and-reference-to-azure-blob-storage-sdk-v12-点网csharp (4认同)

Chr*_*der 8

经过大量的搜索,我找到了一些关于此的 Microsoft 文档:https : //docs.microsoft.com/en-us/azure/storage/blobs/storage-blob-user-delegation-sas-create-dotnet

这详细说明了使用用户委托密钥来生成 SAS 而不是帐户密钥,但更改只是 .ToSasQueryParameters() 的不同重载,如其他答案中所述。

文章中的一些关键片段将其联系起来。首先创建您的 BlobServiceClient:

// Construct the blob endpoint from the account name.
string blobEndpoint = string.Format("https://{0}.blob.core.windows.net", accountName);

// Create a new Blob service client with Azure AD credentials.
BlobServiceClient blobClient = new BlobServiceClient(new Uri(blobEndpoint),
                                                     new DefaultAzureCredential());
Run Code Online (Sandbox Code Playgroud)

获取用户委托密钥,这将用于生成 SAS:

// Get a user delegation key for the Blob service that's valid for seven days.
// You can use the key to generate any number of shared access signatures over the lifetime of the key.
UserDelegationKey key = await blobClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow,
                                                                   DateTimeOffset.UtcNow.AddDays(7));
Run Code Online (Sandbox Code Playgroud)

最后创建 SAS URI:

// Create a SAS token that's valid for one hour.
BlobSasBuilder sasBuilder = new BlobSasBuilder()
{
    BlobContainerName = containerName,
    BlobName = blobName,
    Resource = "b",
    StartsOn = DateTimeOffset.UtcNow,
    ExpiresOn = DateTimeOffset.UtcNow.AddHours(1)
};

// Specify read permissions for the SAS.
sasBuilder.SetPermissions(BlobSasPermissions.Read);

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

// Construct the full URI, including the SAS token.
UriBuilder fullUri = new UriBuilder()
{
    Scheme = "https",
    Host = string.Format("{0}.blob.core.windows.net", accountName),
    Path = string.Format("{0}/{1}", containerName, blobName),
    Query = sasToken
};
Run Code Online (Sandbox Code Playgroud)


Kaa*_*yan 5

使用适用于 .NET 的 Azure Blob 存储客户端库 v12:

BlobSasBuilder blobSasBuilder = new BlobSasBuilder()
{
    BlobContainerName = blobContainerName,
    BlobName = blobName,
    Resource = "b", //b = blob, c = container
    StartsOn = DateTimeOffset.UtcNow,
    ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(lifetimeMinutes)
};

blobSasBuilder.SetPermissions(BlobSasPermissions.Read);

StorageSharedKeyCredential storageSharedKeyCredential = new StorageSharedKeyCredential(accountName, accountKey);

string sas = blobSasBuilder.ToSasQueryParameters(storageSharedKeyCredential).ToString();
Run Code Online (Sandbox Code Playgroud)

如果必须根据分配给容器的访问策略生成共享访问签名(SAS 令牌),请使用以下方法

BlobSasBuilder blobSasBuilder = new BlobSasBuilder()
{
    BlobContainerName = blobContainerName,
    BlobName = blobName,
    Resource = "b", //b = blob, c = container
    Identifier = "ReadOnlyPolicy" //string value referees to the access policy created and assigned to the container.
};

StorageSharedKeyCredential storageSharedKeyCredential = new StorageSharedKeyCredential(accountName, accountKey);

string sas = blobSasBuilder.ToSasQueryParameters(storageSharedKeyCredential).ToString();
Run Code Online (Sandbox Code Playgroud)

注意:当 SAS 令牌生成基于分配给容器的访问策略时,您将无法在 BlobSasBuilder 中定义权限、开始或结束时间。您将收到运行时异常,因为“访问策略字段可以与签名或 SAS 标识符关联,但不能与两者关联”

参考: https: //www.craftedforeveryone.com/beginners-guide-and-reference-to-azure-blob-storage-sdk-v12-dot-net-csharp/

https://www.craftedforeveryone.com/beginners-guide-and-reference-to-azure-blob-storage-sdk-v12-dot-net-csharp/#generate_access_policy_based_sas_token_for_a_blob