Enabling CORS (Cross Origin Resource Sharing) For Your Microsoft Azure Storage (Blobs, etc)

12 January 2015

Just a quick post about enabling CORS access for your Azure storage resources - I found most of the instructions I needed on this very helpful blog post. There's a code snippet on how to add the CORS rule to a Blob Service, but for the lazy / efficient ones, here's a little complete console app you can run:

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            CloudStorageAccount account = CloudStorageAccount.Parse("<<CONNECTION_STRING>>");

            ConfigureCors(account);
        }


        private static void ConfigureCors(CloudStorageAccount storageAccount)
        {
            var blobClient = storageAccount.CreateCloudBlobClient();

            var serviceProperties = blobClient.GetServiceProperties();

            var cors = new CorsRule();

            cors.AllowedOrigins.Add("*");
            //cors.AllowedOrigins.Add("mysite.com"); // more restrictive may be preferable
            cors.AllowedMethods = CorsHttpMethods.Get;
            cors.MaxAgeInSeconds = 3600;

            serviceProperties.Cors.CorsRules.Add(cors);

            blobClient.SetServiceProperties(serviceProperties);
        }

    }
}

You'll only need to run this once, and you do need Version 3.0+ of the Azure Storage Client Libraries. Enjoy!

Tags: Azure, CORS, Blob

Add a Comment

No Comments