Как определить, истек ли срок действия токена SAS для доступа к контейнеру хранилища BLOB-объектов Azure?

я использую клиентскую библиотеку хранилища BLOB-объектов Azure v11 для .Net.

Я написал программу, которую наши клиенты могут использовать для загрузки файлов. Я создаю URL-адрес с токеном SAS (действительным в течение x дней) для нашего клиента, и клиент может загружать файлы с помощью программы. Вот пример URL:

https://storage.blob.core.windows.net/123456789?sv=2019-07-07&sr=c&si=mypolicy&sig=ASDH845378ddsaSDdase324234234rASDSFR

Как я могу узнать, действителен ли токен SAS, до начала загрузки?

Обновление:

В моем URL нет никаких претензий se. Вот мой код для генерации URL:

     var policyName = "mypolicy";

     string containerName = "123456789";

     // Retrieve storage account information from connection string
     CloudStorageAccount storageAccount = CloudStorageAccount.Parse(GetSecret());

     // Create a blob client for interacting with the blob service.
     CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

     // Create a container for organizing blobs within the storage account.
     CloudBlobContainer container = blobClient.GetContainerReference(containerName);
     try
     {
        // The call below will fail if the sample is configured to use the storage emulator in the connection string, but 
        // the emulator is not running.
        // Change the retry policy for this call so that if it fails, it fails quickly.
        BlobRequestOptions requestOptions = new BlobRequestOptions() { RetryPolicy = new NoRetry() };
        await container.CreateIfNotExistsAsync(requestOptions, null);
     }
     catch (StorageException ex)
     {
        MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        return string.Empty;
     }

     // create the stored policy we will use, with the relevant permissions and expiry time
     var storedPolicy = new SharedAccessBlobPolicy()
     {
        SharedAccessExpiryTime = DateTime.UtcNow.AddDays(7),
        Permissions = SharedAccessBlobPermissions.Read |
                       SharedAccessBlobPermissions.Write |
                       SharedAccessBlobPermissions.List
     };

     // get the existing permissions (alternatively create new BlobContainerPermissions())
     var permissions = container.GetPermissions();

     // optionally clear out any existing policies on this container
     permissions.SharedAccessPolicies.Clear();
     // add in the new one
     permissions.SharedAccessPolicies.Add(policyName, storedPolicy);
     // save back to the container
     container.SetPermissions(permissions);

     // Now we are ready to create a shared access signature based on the stored access policy
     var containerSignature = container.GetSharedAccessSignature(null, policyName);
     // create the URI a client can use to get access to just this container

     return container.Uri + containerSignature;

person d1no    schedule 02.09.2020    source источник
comment
Возможно, вы можете обратиться к этому официальному document, поскольку маркер sas обычно содержит поле se, вы можете использовать его, чтобы определить, когда он истекает.   -  person Frank Gong    schedule 02.09.2020


Ответы (1)


Я сам нашел решение. В этом блоге описаны две разные подписи ShardedAccessSignature. Я адаптировал код, так что теперь у меня также есть утверждение se в моем URL-адресе.

Решение:

    protected void GetSharedAccessSignature(
   String containerName, String blobName)
{
    CloudStorageAccount cloudStorageAccount =
       CloudStorageAccount.FromConfigurationSetting(“DataConnectionString”);
    CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
    CloudBlobContainer cloudBlobContainer =
       new CloudBlobContainer(containerName, cloudBlobClient);
    CloudBlockBlob cloudBlockBlob =
         cloudBlobContainer.GetBlockBlobReference(blobName);
    SharedAccessPolicy sharedAccessPolicy = new SharedAccessPolicy();
    sharedAccessPolicy.Permissions = SharedAccessPermissions.Read;
    sharedAccessPolicy.SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-10);
    sharedAccessPolicy.SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(40);
    String sharedAccessSignature1 =
        cloudBlockBlob.GetSharedAccessSignature(sharedAccessPolicy);
    String sharedAccessSignature2 =
       cloudBlockBlob.GetSharedAccessSignature( new SharedAccessPolicy(), “adele”);
}

SharedAccessSignature1 содержит утверждение se. В коде моих первоначальных вопросов я использовал sharedAccessSignature2.

person d1no    schedule 03.09.2020