Icee
Icee

Reputation: 53

Enable CORS for web api deployed in authentication enabled azure web app service

I'm having this weird issue with CORS where it works if I turn off the authentication in my azure web app service.

Setup:

  1. Web API is accessed by a page from a different sharepoint online site.
  2. API is deployed in an Azure APP service. Authentication is enabled.
  3. I configured to add the headers globally via the global.asax.

       Context.Response.AddHeader("Access-Control-Allow-Origin", "*");
        Context.Response.AddHeader("Access-Control-Allow-Headers",
            "Origin, X-Requested-With, Content-Type, Accept,MaxDataServiceVersion");
        Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
    

Results:

  1. I tried disabling the authentication. Of course that's not going to happen in live. But the request is successful, and CORS does not block anything.
  2. I enabled the authentication back, CORS headers are added to the API URL, but the whole request does not work because the authentication url from the default microsoft login is being blocked.

I did allow all origins just to see if the headers are added, but it keeps blocking it somehow for the authentication url.

Has anyone encountered this before? or am I missing a setup somewhere?

Thanks in advance.

Upvotes: 2

Views: 2480

Answers (1)

Tom Sun
Tom Sun

Reputation: 24529

I think you cannot define multiple origin site via the web config? Is there a way to do this just with web. config or a custom code is needed to achieve this?

We could enable CORS for Azure WebApp easily with Azure portal. You use * to allow all origins to make cross-orgin calls. We could get more information about azure webapp CORS from this tutorial.

Cross-Origin Resource Sharing (CORS) allows JavaScript code running in a browser on an external host to interact with your backend. Specify the origins that should be allowed to make cross-origin calls (for example: http://example.com:12345). To allow all, use "*" and remove all other origins from the list. Slashes are not allowed as part of domain or after TLD.

enter image description here

Update:

This is a known limitation of the Azure Portal which should be fixed in the future.

As you mentioned that on the allows-credentials with CORS thing. It's not supported if you use the portal CORS feature, but if you disable it (by removing all the domains there), you can handle CORS inside your code and customize it

For more information, please refer to this blog.

Upvotes: 2

Related Questions