47

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?

0

10 Answers 10

78

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

3
  • 1
    Please note that, Azure resets this setting to default after Maximum age property expires. Commented Apr 2, 2017 at 15:00
  • i have the same problem but adding this does not allow me to use a get-command, it still tells me: Failed to load xxx.jpg: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:4650' is therefore not allowed access.
    – Ewald Bos
    Commented Jul 27, 2018 at 17:55
  • I'm not able to save this rule. I get the following error when I try this on my storage account in the portal: "Failed to save CORS rules for 1 out of 1 services Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature." Commented Jun 9, 2019 at 5:24
25

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.

5
  • Thank you very much. I'll looking for tools. Just tried AzureStorageExplorer. It cannot set * to the AllowedOrgin field. Very strange! Trying other tools ...
    – Zach
    Commented Mar 6, 2015 at 9:07
  • Isn't it odd that such an important thing can't be done through the portal?
    – Tom
    Commented Mar 29, 2016 at 10:19
  • Useful response, but is it possible to enable CORS on a per-container basis? Commented May 31, 2016 at 15:17
  • @MarkShapiro No. Please see my answer here for the reason for that: stackoverflow.com/questions/36543488/…. Commented May 31, 2016 at 15:45
  • 3
    It is finally available in the UI, see my answer below stackoverflow.com/a/41351674/1671558 Commented Dec 27, 2016 at 20:17
16

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

13

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
  • Is it a good practice to all all methods ? @sajeetharan Commented Jul 7, 2021 at 7:21
  • 1
    @SharonWatinsan, In a production environment, it is better to add only the required methods. However, adding "OPTIONS" is still mandatory to handle the CORS issue. Commented Dec 14, 2021 at 12:59
5

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
1
4

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://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-reference-customize-ui-custom

1
3

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
1
2

In 2023, CORS has been renamed in the Azure Portal to "Resource Sharing (CORS) and is under the "Settings" group on the left.

enter image description here

1

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

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");
    }
});
4
  • It looks like Azure does support CORS. Here's a demo project with the setup details: code.msdn.microsoft.com/windowsapps/… Commented Mar 6, 2015 at 8:20
  • Many thanks. I'll try to configure the server side first according to the anwser from Gaurav Mantri.
    – Zach
    Commented Mar 6, 2015 at 8:47
  • @RoryMcCrossan Didn't work for me. I tried with angular setting httpclient header options as 'Access-Control-Allow-Origin':'*', 'Access-Control-Allow-Methods': 'OPTIONS, GET',
    – Shad
    Commented Dec 22, 2022 at 12:24
  • 1
    @Kid the CORS headers need to be set on the server in the response, not in your Angular client sending the request. You can do this through the Azure REST API or the Azure portal Commented Dec 22, 2022 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.