Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure CORS setting for Blob storage in windows azure

I have created several containers in a azure storage and also uploaded some files into these containers. Now I need to give domain level access to the container/blobs. So I tried it from code level like below.

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
        CloudConfigurationManager.GetSetting("StorageConnectionString"));

        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        ServiceProperties blobServiceProperties = new ServiceProperties();
            blobServiceProperties.Cors.CorsRules.Add(new CorsRule(){
                AllowedHeaders = new List<string>() {"*"},
                ExposedHeaders = new List<string>() {"*"},
                AllowedMethods = CorsHttpMethods.Post | CorsHttpMethods.Put | CorsHttpMethods.Get | CorsHttpMethods.Delete ,
                AllowedOrigins = new List<string>() { "http://localhost:8080/"},
                MaxAgeInSeconds = 3600,
            });

          blobClient.SetServiceProperties(GetBlobServiceProperties());  

But above code seems to be work if I am creating everything from code (Correct me if I am wrong). I also find setting like below Here,

 <CorsRule>
  <AllowedOrigins>http://www.contoso.com, http://www.fabrikam.com</AllowedOrigins>
  <AllowedMethods>PUT,GET</AllowedMethods>
  <AllowedHeaders>x-ms-meta-data*,x-ms-meta-target,x-ms-meta-source</AllowedHeaders>
  <ExposedHeaders>x-ms-meta-*</ExposedHeaders>
  <MaxAgeInSeconds>200</MaxAgeInSeconds>
</CorsRule>

But I didn't get where this code have to put. I mean in which file. Or is there any setting for CORS while creating container or blob from azure portal. Please assist. Any help would be appreciable. Thanks!

like image 633
Rajaram Shelar Avatar asked Feb 19 '15 14:02

Rajaram Shelar


People also ask

How do I enable CORS on Azure blob storage?

To enable CORS, you need to set the appropriate service properties using version 2013-08-15 or later for the Blob, Queue, and Table services, or version 2015-02-21 or for the File service. You enable CORS by adding CORS rules to the service properties.

How do I set CORS config?

In the Cross-origin resource sharing (CORS) section, choose Edit. In the CORS configuration editor text box, type or copy and paste a new CORS configuration, or edit an existing configuration. The CORS configuration is a JSON file. The text that you type in the editor must be valid JSON.


1 Answers

The following answers the question that was actually asked in the title. It appears the questioner already knew how to do this largely from his code, but here is my answer to this. Unfortunately the code samples MS has put out has been far from easy or clear, so I hope this helps someone else. In this solution all you need is a CloudStorageAccount instance, which you can call this function from then (as an extension method).

// USAGE:

        // -- example usage (in this case adding a wildcard CORS rule to this account --

        CloudStorageAccount acc = getYourStorageAccount();

        acc.SetCORSPropertiesOnBlobService(cors => {
            var wildcardRule = new CorsRule() { AllowedMethods = CorsHttpMethods.Get, AllowedOrigins = { "*" } };
            cors.CorsRules.Add(wildcardRule);
            return cors;
        });

// CODE:

    /// <summary>
    /// Allows caller to replace or alter the current CorsProperties on a given CloudStorageAccount.
    /// </summary>
    /// <param name="storageAccount">Storage account.</param>
    /// <param name="alterCorsRules">The returned value will replace the 
    /// current ServiceProperties.Cors (ServiceProperties) value. </param>
    public static void SetCORSPropertiesOnBlobService(this CloudStorageAccount storageAccount,
        Func<CorsProperties, CorsProperties> alterCorsRules)
    {
        if (storageAccount == null || alterCorsRules == null) throw new ArgumentNullException();

        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        ServiceProperties serviceProperties = blobClient.GetServiceProperties();

        serviceProperties.Cors = alterCorsRules(serviceProperties.Cors) ?? new CorsProperties();

        blobClient.SetServiceProperties(serviceProperties);
    }

It may be helpful to consider the properties of the CorsRule class:

        CorsRule corsRule = new CorsRule() {
            AllowedMethods = CorsHttpMethods.Get,       // Gets or sets the HTTP methods permitted to execute for this origin
            AllowedOrigins = { "*" },                   // (IList<string>) Gets or sets domain names allowed via CORS.
            //AllowedHeaders = { "*" },                 // (IList<string>) Gets or sets headers allowed to be part of the CORS request
            //ExposedHeaders = null,                    // (IList<string>) Gets or sets response headers that should be exposed to client via CORS
            //MaxAgeInSeconds = 33333                   // Gets or sets the length of time in seconds that a preflight response should be cached by browser
        };
like image 116
Nicholas Petersen Avatar answered Nov 10 '22 00:11

Nicholas Petersen