26. april 2011 21:03
To start with, I did not think I would write a blog post about Azure Shared Access Signatures (SAS). But after having worked with them for some time I had stumbled into some things I think is worth sharing. The things I found is shown bellow the code. Thanks to @Danielovich for pointing me in the right direction.
I'll start by showing how to create a SAS. You need to have access to the Primary Access Key (or the Secondary Access Key) for the blob storage that you wish to use. These keys can be obtained through the Windows Azure Platform Portal. The code below shows how to create a SAS, use it and what you can/can not do with it.
/* Here is how to create the SAS */
StorageCredentialsAccountAndKey masterCredentials =
new StorageCredentialsAccountAndKey("[Name]", "[AccessKey]");
CloudStorageAccount account = new CloudStorageAccount(masterCredentials, false);
CloudBlobClient client = account.CreateCloudBlobClient();
CloudBlobContainer container = client.GetContainerReference("mytestcontainer");
SharedAccessPolicy sharedAccessPolicy = new SharedAccessPolicy();
sharedAccessPolicy.SharedAccessStartTime = DateTime.UtcNow;
sharedAccessPolicy.SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromHours(1);
string sharedAccessSignature = container.GetSharedAccessSignature(sharedAccessPolicy);
/* Here is how to use the sharedAccessSignature */
StorageCredentialsSharedAccessSignature sasCredentials =
CloudBlobClient sasClient = new CloudBlobClient(account.BlobEndpoint, sasCredentials);
CloudBlobContainer sasContainer = sasClient.GetContainerReference("mytestcontainer");
CloudBlob sasBlob = sasContainer.GetBlobReference("myblob.txt");
/* This will work if SharedAccessPermissions.Write is used */
/* This will work if SharedAccessPermissions.Read is used */
/* This will work if SharedAccessPermissions.Delete is used */
/* This will work if SharedAccessPermissions.List is used */
/* This will always fail */
/* This will always fail */
Here are some points that I think is worth noting when working with SAS. It might even save you some time:
- Remember to use Utc methods on DateTime. If you use anything else, the time window where the SAS is valid, might not be the same as you think.
- The FetchAttributes method does not work on the container/blob that the SAS was generated for. This is interesting because the FetchAttributes method is very often used to determine if the container/blob exists or not. But it will work for blobs inside a container if the SAS was generated for that container.
- A StorageClientException with the message: The specified resource does not exist, is thrown if the SAS does not grand enough access. So Azure hides the container/blob if the client does not have the right access level.
- DeleteIfExists will never fail if SharedAccessPermissions.Delete is not specified. As mentioned above, Azure hides containers/blobs if access rights are missing.