25
votes

We have a blob storage on Windows Azure.

http://mytest.blob.core.windows.net/forms

I uploaded a few files to the storage using CloudBerry. And I can download the files by browsers successfully. These files are simple text files, but with different file extensions. For example,

http://mytest.blob.core.windows.net/forms/f001.etx

I want to download the files via jquery ($.get), however, it failed because of CORS.

How can I configure CORS in Azure BLOB Storage in Portal?

And, should I do something for CORS in the client side too?

9

9 Answers

43
votes

This is possible to do now directly in the portal fortunately. If you just select the account, you will see the menu with various options and CORS will be one of them for each of the services Blob, File, etc.

enter image description here enter image description here

22
votes

UPDATE: At the time of this answer the Azure Portal did not have this feature. It does now as outlined here. The following outlines the way to do this before the UI was added.

How can I configure CORS in Azure BLOB Storage in Portal?

If you want you can always set the CORS rules for blob storage programmatically. If you're using .Net Storage Client library, check out this blog post from storage team: http://blogs.msdn.com/b/windowsazurestorage/archive/2014/02/03/windows-azure-storage-introducing-cors.aspx. Code for setting CORS setting from that blog post:

private static void InitializeCors()
{
     // CORS should be enabled once at service startup
     // Given a BlobClient, download the current Service Properties 
     ServiceProperties blobServiceProperties = BlobClient.GetServiceProperties();
     ServiceProperties tableServiceProperties = TableClient.GetServiceProperties();

     // Enable and Configure CORS
     ConfigureCors(blobServiceProperties);
     ConfigureCors(tableServiceProperties);

     // Commit the CORS changes into the Service Properties
     BlobClient.SetServiceProperties(blobServiceProperties);
     TableClient.SetServiceProperties(tableServiceProperties);
}

private static void ConfigureCors(ServiceProperties serviceProperties)
{
    serviceProperties.Cors = new CorsProperties();
    serviceProperties.Cors.CorsRules.Add(new CorsRule()
    {
        AllowedHeaders = new List<string>() { "*" },
        AllowedMethods = CorsHttpMethods.Put | CorsHttpMethods.Get | CorsHttpMethods.Head | CorsHttpMethods.Post,
        AllowedOrigins = new List<string>() { "*" },
        ExposedHeaders = new List<string>() { "*" },
        MaxAgeInSeconds = 1800 // 30 minutes
     });
}

If you're looking for a tool to do the same, a few storage explorers have support for configuring CORS - Azure Storage Explorer, Cerebrata Azure Management Studio, Cloud Portam (Disclosure - I'm building Cloud Portam utility).

Once the CORS is configured properly, you can use the code mentioned in Rory's answer to download the file from blob storage. You don't have to do anything special on the client side as mentioned by Rory.

7
votes

If you want to access blob storage JSON file as rest API then you should be enable CORS from the storage account. Go Inside the storage account > CORS > Blob service > then set all required values. enter image description here

5
votes

Now you can easily set/edit/view CORS rules using azure power shell. Find more information on this link:

https://azure.microsoft.com/en-us/documentation/articles/storage-powershell-guide-full/

To summarize following power shell commands will set the CORS for your blob:

  1. Run Add-AzureAccount to sign into your account
  2. See your subscriptions in azure Get-AzureSubscription | Format-Table SubscriptionName, IsDefault, IsCurrent, CurrentStorageAccountName
  3. Set desired subscription $SubscriptionName = 'Your subscription name'
  4. Check your desired blob Get-AzureStorageBlob
  5. Now you need to create authorization context for your blob $ctx = New-AzureStorageContext and enter desired parameters.
  6. You are now ready to get or set CORS rules for your blob. Check current CORS rules Get-AzureStorageCORSRule -ServiceType Blob -Context $ctx
  7. Set current CORS rules for example: $CorsRules = (@{ AllowedHeaders=@("*"); AllowedOrigins=@("*"); ExposedHeaders=@("content-length"); MaxAgeInSeconds=200; AllowedMethods=@("Get","Connect", "Head")})
  8. Set-AzureStorageCORSRule -ServiceType Blob -CorsRules $CorsRules -Context $ctx
3
votes

A more terse way of setting CORS via PowerShell: https://gist.github.com/irwinwilliams/4cf93b6e2461c753ff125590650186ae

#works with Azure in Powershell v 1.3.2
clear 
$StorageAccountName = "[storageaccountname]"
$Key = "[storageaccountkey]"
$Context = New-AzureStorageContext -StorageAccountKey $Key -StorageAccountName $StorageAccountName
$CorsRules = (@{
    AllowedHeaders=@("*");
    AllowedOrigins=@("*");
    ExposedHeaders=@("content-length");
    MaxAgeInSeconds=200;
    AllowedMethods=@("Get","Connect", "Head")})
Set-AzureStorageCORSRule -ServiceType Blob -CorsRules $CorsRules -Context $Context
$CORSrule = Get-AzureStorageCORSRule -ServiceType Blob -Context $Context
echo "Current CORS rules: "
echo $CORSrule
3
votes

With the new Interface in Azure portal you can simply enable CORS by navigating to your Storage Account

enter image description here

and then enable CORS with the necessary settings

enter image description here

2
votes

To ensure that your B2C customization works, you need to take care of below things:

  1. Ensure your content is HTML5 compliant and accessible
  2. Ensure your content server is enabled for CORS. Link: How can I set CORS in Azure BLOB Storage in Portal?
  3. (Very Important)Serve content over HTTPS.
  4. (optional)Use absolute URLS such as https://yourdomain/content for all links and CSS content.

Tip: to verify that the site you are hosting your content on has CORS enabled and test CORS requests, you can use the site http://test-cors.org/. Thanks to this site, you can simply either send the CORS request to a remote server (to test if CORS is supported), or send the CORS request to a test server (to explore certain features of CORS).

Reference Link: https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-reference-customize-ui-custom

1
votes

This is how i enabled cors with a Console Application, just provide your credentials inside StorageCredentials:

private static CloudStorageAccount StorageAccount;

    public static CloudBlobClient BlobClient
    {
        get;
        private set;
    }

    static void Main(string[] args)
    {

        StorageAccount = new CloudStorageAccount(new StorageCredentials("AccountName", "AccountKey"), true);
        BlobClient = StorageAccount.CreateCloudBlobClient();

        InitializeCors(BlobClient);
    }

    private static void InitializeCors(CloudBlobClient blobClient)
    {           
        ServiceProperties blobServiceProperties = BlobClient.GetServiceProperties();

        ConfigureCors(blobServiceProperties);

        BlobClient.SetServiceProperties(blobServiceProperties);         
    }

    private static void ConfigureCors(ServiceProperties serviceProperties)
    {
        serviceProperties.Cors = new CorsProperties();
        serviceProperties.Cors.CorsRules.Add(new CorsRule()
        {
            AllowedHeaders = new List<string>() { "*" },
            AllowedMethods = CorsHttpMethods.Put | CorsHttpMethods.Get | CorsHttpMethods.Head | CorsHttpMethods.Post,
            AllowedOrigins = new List<string>() { "*" },
            ExposedHeaders = new List<string>() { "*" },
            MaxAgeInSeconds = 1800 // 30 minutes
        });
    }
0
votes

Azure Blob storage supports CORS, but you need to set the headers before making the request. To do this it would be better to use $.ajax as it gives you more control over the information being sent. Here's a re-worked example of this demo:

function setHeader(xhr) {
    xhr.setRequestHeader('x-ms-version', '2013-08-15');
    xhr.setRequestHeader('MaxDataServiceVersion', '3.0');
    xhr.setRequestHeader('Accept', 'application/json;odata=nometadata');
}

$.ajax({
    type: 'GET',
    datatype: "json",
    url: 'http://mytest.blob.core.windows.net/forms/f001.etx',
    beforeSend: setHeader,
    success: function(data) {
        // do something with the retrieved file.
    },
    error: function (res, status, xhr) {
        alert("can't get the data for the specified table");
    }
});