具有IP范围限制的Azure Blob SAS

时间:2019-02-06 00:36:24

标签: azure-storage azure-storage-blobs

我正在尝试创建SAS URI /令牌,以允许下载我的Azure存储Blob。

我想在blob级别上执行此操作,以免无意中授予对意外资源的访问权限。

我用于执行此操作的当前代码是:

public static string GetBlobSasUri(string containerName, string reference)
{
    // Create the CloudBlobContainer object
    CloudBlobContainer container = blobClient.GetContainerReference(containerName);
    container.CreateIfNotExists();

    // Get a reference to a blob within the container.
    CloudBlockBlob blob = container.GetBlockBlobReference(reference);

    // Set the expiry time and permissions for the blob.
    // In this case, the start time is specified as a few minutes in the past, to mitigate clock skew.
    // The shared access signature will be valid immediately.
    SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();
    sasConstraints.SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5);
    sasConstraints.SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMonths(1);
    sasConstraints.Permissions = SharedAccessBlobPermissions.Read;

    // Generate the shared access signature on the blob, setting the constraints directly on the signature.
    string sasBlobToken = blob.GetSharedAccessSignature(sasConstraints);

    // Return the URI string for the container, including the SAS token.
    return blob.Uri + sasBlobToken;
}

这主要基于此处文档中的示例:

Generate a shared access signature URI for a blob

这有效。但是,我在其他SAS文档中看到也可以限制为某个IP范围:

Service SAS Uri Example

我对SAS令牌的理解是签名对所有参数进行签名,所以我认为这并不像将我的IP范围附加到从我上面粘贴的代码返回的SAS URI上那样容易,因为签名随后不匹配。

但是,SharedAccessBlobPolicy仅具有三个字段,分别是访问的开始/结束时间以及权限。我没有看到有关IP范围的任何信息。

在Blob级别而不是为完整帐户生成SAS URI时,是否可以设置这些允许的范围?

1 个答案:

答案 0 :(得分:1)

请使用以下代码:

        public static string GetBlobSasUri(string ipAddressFrom, string ipAddressTo)
        {
            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials("account_name", "account_key"), true);
            CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
            var cloudBlobContainer = cloudBlobClient.GetContainerReference("test-1");

            cloudBlobContainer.CreateIfNotExists();

            CloudBlockBlob blob = cloudBlobContainer.GetBlockBlobReference("a.txt");

            var ipAddressRange = new IPAddressOrRange(ipAddressFrom, ipAddressTo);

            var sasBlobToken = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
            {
                Permissions = SharedAccessBlobPermissions.List,
                SharedAccessExpiryTime = new DateTimeOffset(DateTime.UtcNow.AddHours(1))
            }, null, null,null, ipAddressRange);


            return blob.Uri + sasBlobToken;
        }