What is CORS?

There are lots of instances that an app will need to call a GET/POST request to another domain (from a different domain where the resource originated). Once the web app starts doing the request, the response will throw an “Access-Control-Allow-Origin” error. Then you ask yourself, what now?

One solution is CORS (Cross-origin resource sharing), which allows all resources (like JavaScript) to make cross origin requests.
Here is an example of how to add CORS Rule to allow a request to Azure storage tables using Azure SDK.

1. Build the connection string

string connectionString= "DefaultEndpointsProtocol=https;
AccountName={account name/storage name};

2. Create the CloudTableClient

CloudStorageAccountstorageAccount = CloudStorageAccount.Parse( connectionString);
CloudTableClient client = storageAccount.CreateCloudTableClient();

3. Add CORS Rule
* as wildcard

CorsRule = new CorsRule()
  AllowedHeaders = new List<string> { "*" },
  AllowedMethods = CorsHttpMethods.Connect | CorsHttpMethods.Delete | CorsHttpMethods.Get | CorsHttpMethods.Head | CorsHttpMethods.Merge
	| CorsHttpMethods.Options | CorsHttpMethods.Post | CorsHttpMethods.Put | CorsHttpMethods.Trace, 
  //Since we'll only be calling Query Tables, let's just allow GET verb
  AllowedOrigins = new List<string> { "*" }, //This is the URL of our application.
  ExposedHeaders = new List<string> { "*" },
  MaxAgeInSeconds = 1 * 60 * 60, //Let the browswer cache it for an hour

4. Add rules to client

ServiceProperties serviceProperties = client.GetServiceProperties();
CorsProperties corsSettings = serviceProperties.Cors;
corsSettings.CorsRules.Add( corsRule );
//Save the rule
client.SetServiceProperties( serviceProperties );
  • After #4, there should already be cors rule connected to an account name.
    In order to double check what cors rules are there for that account name, we can use:

    ServiceProperties serviceProperties = client.GetServiceProperties();
    CorsProperties corsSettings = serviceProperties.Cors;

NOTE: If we need to put cors rule for blobs, we will just change CreateCloudTableClient():
CloudBlobClient client = storageAccount.CreateCloudBlobClient();

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>