使用 .NET 创建存储访问策略

存储访问策略对服务器端的服务级别共享访问签名 (SAS) 提供另一级别的控制。 定义存储访问策略可以将共享访问签名分组到一起,并为通过策略绑定的共享访问签名提供其他限制。 可以使用存储访问策略更改 SAS 的开始时间、到期时间或权限,或者在颁发 SAS 后将其吊销。

以下 Azure 存储资源支持存储访问策略:

  • Blob 容器
  • 文件共享
  • 队列

注意

容器上的存储访问策略可以与共享访问签名相关联,后者授予对容器本身的权限,或对它包含的 Blob 的权限。 类似地,文件共享上的存储访问策略可以与共享访问签名相关联,后者授予对共享本身的权限,或对它包含的文件的权限。

仅服务 SAS 支持存储访问策略。 帐户 SAS 或用户委托 SAS 不支持存储的访问策略。

有关存储访问策略的更多信息,请参阅创建存储访问策略

创建存储访问策略

创建存储访问策略的基础 REST 操作是设置容器 ACL。 你必须通过使用连接字符串中的帐户访问密钥,授权该操作通过共享密钥创建存储访问策略。 不支持使用 Microsoft Entra 凭据授权“设置容器 ACL”操作。 有关详细信息,请参阅调用数据操作的权限

以下代码示例会在容器上创建存储访问策略。 可以使用访问策略指定对容器或其 Blob 上的服务 SAS 的约束。

若要使用适用于 Azure 存储的 .NET 客户端库版本 12 在容器上创建存储访问策略,请调用以下方法之一:

以下示例创建一个有效期为一天并授予读/写权限的存储访问策略:

async static Task CreateStoredAccessPolicyAsync(string containerName)
{
    string connectionString = "";

    // Use the connection string to authorize the operation to create the access policy.
    // Azure AD does not support the Set Container ACL operation that creates the policy.
    BlobContainerClient containerClient = new BlobContainerClient(connectionString, containerName);

    try
    {
        await containerClient.CreateIfNotExistsAsync();

        // Create one or more stored access policies.
        List<BlobSignedIdentifier> signedIdentifiers = new List<BlobSignedIdentifier>
        {
            new BlobSignedIdentifier
            {
                Id = "mysignedidentifier",
                AccessPolicy = new BlobAccessPolicy
                {
                    StartsOn = DateTimeOffset.UtcNow.AddHours(-1),
                    ExpiresOn = DateTimeOffset.UtcNow.AddDays(1),
                    Permissions = "rw"
                }
            }
        };
        // Set the container's access policy.
        await containerClient.SetAccessPolicyAsync(permissions: signedIdentifiers);
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine(e.ErrorCode);
        Console.WriteLine(e.Message);
    }
    finally
    {
        await containerClient.DeleteAsync();
    }
}

另请参阅

资源

有关使用已弃用的 .NET 版本 11.x SDK 的相关代码示例,请参阅使用 .NET 版本 11.x 的代码示例