Sun, 02 May 2010

Shared Access Signatures Are Easy These Days

I wrote a blog post back when Shared Access Signatures were first released called “New Storage Feature: Shared Access Signatures,” which gave some sample code to use what was then a brand new feature in Windows Azure storage (and not supported by the storage client library).

These days, using Shared Access Signatures is much simpler. I just wrote some .NET code that uses the Microsoft.WindowsAzure.StorageClient library to do the following:

  1. Create a blob.
  2. Generate a Shared Access Signature (SAS) for that blob that allows read and write access.
  3. Display a working URL to the blob.
  4. Modify and read back the blob using only the SAS for authorization.

Here’s the code:

// regular old blob storage
var account = CloudStorageAccount.DevelopmentStorageAccount; // or your cloud account
var container = account
var blob = container.GetBlobReference("test.txt");
blob.Properties.ContentType = "text/plain";
blob.UploadText("Hello, World!");

// create a shared access signature (looks like a query param: ?se=...)
var sas = blob.GetSharedAccessSignature(new SharedAccessPolicy()
        Permissions = SharedAccessPermissions.Read
        SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromMinutes(5)
Console.WriteLine("This link should work for the next five minutes:");
Console.WriteLine(blob.Uri.AbsoluteUri + sas);

// now just use the SAS to do blob operations
var sasCreds = new StorageCredentialsSharedAccessSignature(sas);
// new client using the same endpoint (including account name),
//   but using the SAS as the credentials
var sasBlob = new CloudBlobClient(account.BlobEndpoint, sasCreds)
sasBlob.UploadText("Hello again!");

There’s nothing more to it than that! For more details about Shared Access Signatures, see “Cloud Cover Episode 8: Shared Access Signatures” or the MSDN documentation on the details of signature itself.

[UPDATE 6/4/2010] I didn’t show how to use Signed Identifiers the first time around, but never fear!  It’s easy too. Here’s how to add an access policy to a container and use that in a Shared Access Signature:

var permissions = container.GetPermissions();
permissions.SharedAccessPolicies.Add("readonly", new SharedAccessPolicy()
        Permissions = SharedAccessPermissions.Read
container.SetPermissions(permissions, new BlobRequestOptions()
    // fail if someone else has already changed the container before we do
    AccessCondition = AccessCondition.IfMatch(container.Properties.ETag)

var sasWithIdentifier = blob.GetSharedAccessSignature(new SharedAccessPolicy()
        SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromDays(7)
    }, "readonly");

Console.WriteLine("This link should work for the next seven days:");
Console.WriteLine(blob.Uri.AbsoluteUri + sasWithIdentifier);