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

C# 如何使用最新的Azure SDK.NET API v12在Blob上获取共享访问签名?,c#,azure,azure-storage-blobs,azure-sas,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.

我曾经能够使用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);

...
var containerName=“mycontainer”;
var blobName=“myblob”;
CloudStorageAccount存储帐户
=CloudStorageAccount.Parse();
CloudBlobClient blobClient=storageAccount.CreateCloudBlobClient();
CloudBlobContainer container=blobClient.GetContainerReference(containerName);
SharedAccessBlobPermissions权限=SharedAccessBlobPermissions.Read;
TimeSpan clockSkew=TimeSpan.FromMinutes(15d);
TimeSpan accessDuration=TimeSpan.FromMinutes(15d);
var blobSAS=新的SharedAccessBlobPolicy
{
SharedAccessStartTime=DateTime.UtcNow.Subtract(时钟偏移),
SharedAccessExpiryTime=DateTime.UtcNow.Add(accessDuration)+时钟偏移,
权限=权限
};
CloudBlockBlob blob=container.GetBlockBlobReference(blobName);
字符串sasBlobToken=blob.GetSharedAccessSignature(blobSAS);
...
我想使用最新的v12.NET API,它似乎将
CloudBlobClient
替换为
BlobServiceClient
CloudBlobContainer
替换为
BlobContainerClient
CloudBlockBlob
替换为
BlobClient

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

问题


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

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

以下是如何在服务器上构建一个:

//  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);
//使用连接字符串创建BlobService的客户端。
var blobServiceClient=新的blobServiceClient(storageConnectionString);
//获取对容器的引用。
var blobContainerClient=blobServiceClient.GetBlobContainerClient();
//获取对容器中blob的引用
BlobClient BlobClient=containerClient.GetBlobClient();
//定义要访问的资源以及允许访问的时间。
var blobSasBuilder=新的blobSasBuilder
{
StartsOn=DateTime.UtcNow.Subtract(时钟偏移),
ExpiresOn=DateTime.UtcNow.Add(accessDuration)+clockSkew,
BlobContainerName=,
BlobName=,
};
//定义权限的类型。
设置权限(BlobSasPermissions.Write);
//生成StorageSharedKeyCredential的实例

var storageSharedKeyCredential=new storageSharedKeyCredential(在此回答之后,显示Azure.Storage命名空间中的所有功能。此链接可用于获取更多信息。

使用Azure Blob存储客户端库v12 for.NET:

        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();
私有字符串BuildSASUri(BlobClient blob)
{
//创建仅允许读取一分钟的用户SAS
BlobSasBuilder sas=新BlobSasBuilder
{
BlobContainerName=blob.BlobContainerName,
BlobName=blob.Name,
Resource=“b”,
ExpiresOn=DateTimeOffset.UtcNow.AddMinutes(1)
};
//允许读访问
sas.SetPermissions(BlobSasPermissions.Read);
var storageSharedKeyCredential=新的storageSharedKeyCredential(
_iconfiguration.GetValue(“StorageAccount:AccountName”),
_iconfiguration.GetValue(“StorageAccount:AccountKey”)
);
返回sas.ToSasQueryParameters(storageSharedKeyCredential.ToString();
}
以上是我的工作代码

但是,我不知道如何使用V12创建存储访问策略。应该是这样的:

但我认为微软完全忘记了提供一种创建BlobSignedIdentifier的方法

这些文件已过期:


它使用了Microsoft.Azure.Storage.Blob,但说不要再使用它。

经过大量的搜索,我找到了一些关于此的Microsoft文档:

这详细说明了如何使用用户委派密钥而不是帐户密钥来生成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());
获取用户委派密钥,这将用于生成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));
最后创建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
};

为.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();
如果必须根据分配给容器的访问策略生成共享访问签名(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();
注意:当SAS令牌生成基于分配给容器的访问策略时,您将无法在BlobSasBuilder中定义权限、开始或结束时间。您将获得运行时异常,因为“访问策略字段可以与签名或SAS标识符相关联,但不能同时与两者相关联”

参考:

此处:说明Azure存储支持三种不同类型的共享访问签名(SAS):

  • 帐户级SAS,这是您在v11 SDK中使用的。详细信息和示例如下:
  • 服务级别SAS,使用v12(&V11)SDK。详细信息和示例如下:
  • 用户委派SAS,这是Microsoft推荐的方法,提供您可以使用Azure Active Directory用户使用v12 SDK进行签名。此处的详细信息和示例:
  • 1和2都使用帐户的共享密钥生成SAS令牌,而3使用从AAD帐户用户生成的密钥,因此更安全,更容易在需要时撤销(理论上)。有关为什么更安全的更多详细信息,请参阅(“此方法提供了额外的安全级别,并避免了将帐户访问密钥与应用程序代码一起存储的需要。因此,使用Azure AD凭据创建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();