Skip to content

Instantly share code, notes, and snippets.

@YidingZhou
Created February 26, 2015 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YidingZhou/0c7bc81b723da3f3daae to your computer and use it in GitHub Desktop.
Save YidingZhou/0c7bc81b723da3f3daae to your computer and use it in GitHub Desktop.
Azure Storage SAS Helpers
/// <summary>
/// create a container if doesn't exist, setting permission with policy, and return assosciated SAS signature
/// </summary>
/// <param name="account">storage account</param>
/// <param name="key">storage key</param>
/// <param name="container">container to be created</param>
/// <param name="policy">name for the policy</param>
/// <param name="start">start time of the policy</param>
/// <param name="end">expire time of the policy</param>
/// <param name="permissions">permission on the name</param>
/// <returns>the SAS for the container, in full URI format.</returns>
public static string CreateContainerWithPolicySASIfNotExist(string account, string key, string container, string policy, DateTime start, DateTime end, SharedAccessBlobPermissions permissions)
{
// 1. form the credentail and initial client
CloudStorageAccount storageaccount = new CloudStorageAccount(new StorageCredentials(account, key), false);
CloudBlobClient client = storageaccount.CreateCloudBlobClient();
// 2. create container if it doesn't exist
CloudBlobContainer storagecontainer = client.GetContainerReference(container);
storagecontainer.CreateIfNotExists();
// 3. validate policy, create/overwrite if doesn't match
bool policyFound = false;
SharedAccessBlobPolicy accesspolicy = new SharedAccessBlobPolicy()
{
SharedAccessExpiryTime = end,
SharedAccessStartTime = start,
Permissions = permissions
};
BlobContainerPermissions blobPermissions = storagecontainer.GetPermissions();
if (blobPermissions.SharedAccessPolicies.ContainsKey(policy))
{
SharedAccessBlobPolicy containerpolicy = blobPermissions.SharedAccessPolicies[policy];
if (!(permissions == (containerpolicy.Permissions & permissions) && start <= containerpolicy.SharedAccessStartTime && end >= containerpolicy.SharedAccessExpiryTime))
{
blobPermissions.SharedAccessPolicies[policy] = accesspolicy;
}
else
{
policyFound = true;
}
}
else
{
blobPermissions.SharedAccessPolicies.Add(policy, accesspolicy);
}
if (!policyFound)
{
storagecontainer.SetPermissions(blobPermissions);
}
// 4. genereate SAS and return
string container_sas = storagecontainer.GetSharedAccessSignature(new SharedAccessBlobPolicy(), policy);
string container_url = storagecontainer.Uri.AbsoluteUri + container_sas;
return container_url;
}
private static string GenerateSAS(string account, string key, string url, DateTime start, DateTime end, bool canread, bool canwrite, bool candelete, bool canlist)
{
if (start.CompareTo(end) > 0)
{
throw new Exception("Start time must be earlier than end time.");
}
SharedAccessBlobPermissions perm = SharedAccessBlobPermissions.None;
if (canread) perm |= SharedAccessBlobPermissions.Read;
if (canwrite) perm |= SharedAccessBlobPermissions.Write;
if (candelete) perm |= SharedAccessBlobPermissions.Delete;
if (canlist) perm |= SharedAccessBlobPermissions.List;
SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();
sasConstraints.SharedAccessStartTime = start;
sasConstraints.SharedAccessExpiryTime = end;
sasConstraints.Permissions = perm;
CloudStorageAccount storageaccount = new CloudStorageAccount(new StorageCredentialsAccountAndKey(account, key), true);
CloudBlobClient blobclient = storageaccount.CreateCloudBlobClient();
if (urlIsBlob(account, key, url))
{
CloudBlob blob = blobclient.GetBlobReference(url);
return blob.Uri + blob.GetSharedAccessSignature(sasConstraints);
}
else if (urlIsContainer(account, key, url))
{
CloudBlobContainer container = blobclient.GetContainerReference(url);
return container.Uri + container.GetSharedAccessSignature(sasConstraints);
}
else
{
throw new Exception("Cannot validate URL");
}
}
private static bool urlIsContainer(string account, string key, string url)
{
CloudStorageAccount storageaccount = new CloudStorageAccount(new StorageCredentialsAccountAndKey(account, key), true);
CloudBlobClient blobclient = storageaccount.CreateCloudBlobClient();
CloudBlobContainer container = blobclient.GetContainerReference(url);
try
{
container.FetchAttributes();
return true;
}
catch
{
return false;
}
}
private static bool urlIsBlob(string account, string key, string url)
{
CloudStorageAccount storageaccount = new CloudStorageAccount(new StorageCredentialsAccountAndKey(account, key), true);
CloudBlobClient blobclient = storageaccount.CreateCloudBlobClient();
CloudBlob blob = blobclient.GetBlobReference(url);
try
{
blob.FetchAttributes();
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Get SAS based on the given blob and policy, this function assumes both blob and the policy exists
/// </summary>
/// <param name="account">storage account</param>
/// <param name="key">storage key</param>
/// <param name="blob">blob url</param>
/// <param name="policy">policy name</param>
/// <returns></returns>
public static string GetBlobSAS(string account, string key, string blob, string policy)
{
// 1. form the credentail and initial client
CloudStorageAccount storageaccount = new CloudStorageAccount(new StorageCredentials(account, key), false);
CloudBlobClient client = storageaccount.CreateCloudBlobClient();
// 2. validate the blob
ICloudBlob storageblob = client.GetBlobReferenceFromServer(new Uri(blob));
storageblob.FetchAttributes(); // if blob doesn't exist, this will throw StorageClientException with StorageErrorCode.ResourceNotFound
// 3. generate SAS and return
string sas = storageblob.GetSharedAccessSignature(new SharedAccessBlobPolicy(), policy);
string url = storageblob.Uri.AbsoluteUri + sas;
return url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment