Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi CORs - Access-Control-Allow-Origin header is present on request error

Question Background:

This seems to be a common issue and one I have fallen foul of.

I have a standard WebApi currently hosted in Azure and a calling AngularJS app that calls an end point on said WebApi.

The AngularJS app URL calling to the WebApi is:

http://siteang.azurewebsites.net

And the WebApi address is:

https://site.azurewebsites.net

I want to ensure that only my app at http://siteang.azurewebsites.net is capable of accessing the WebApi at https://site.azurewebsites.net

The Issue:

I am receiving the following error on the submitting form of my AngularJS app to the WebApi service.

XMLHttpRequest cannot load https://site.azurewebsites.net/api/ShoppingComparison/GetC…itemIndex=Baby&itemtosearch=baby&lowToHigh=false&maxPrice=50000&minPrice=0.

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://siteang.azurewebsites.net' is therefore not allowed access. The response had HTTP status code 500.

The Code:

The following is the $http request to the WebApi service.

Note that the header property of the call has been set with the address of the AngularJS site.

   loadSearchList: function (itemToSearch, itemIndex, countryCode) {
        self.itemToSearch = itemToSearch;
        self.itemCatagory = itemIndex;
        self.country = countryCode;

        self.searchList = [];

        $http({
            method: 'GET',
            url: 'https://site.azurewebsites.net/api/ShoppingComparison/GetComparisons',
            params: {
                itemtosearch: itemToSearch,
                itemIndex: itemIndex,
                countryCode: countryCode,
                maxPrice: '50000',
                minPrice: '0',
                highToLow: true,
                lowToHigh: false,
                amazonEbay: true,
                amazonOnly: false,
                ebayOnly: false
            },
            headers: {
                'Content-Type': 'text/plain; charset=UTF-8',
                'Access-Control-Allow-Origin': 'http://siteang.azurewebsites.net',
                'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE'
            }
        }).success(function (data) {

            //Success Handler.

        }).error(function (data) {

            //Error Handler.

        });

    }

The following is the WebApi Controller that is being calling by the AngularJS app. Note that the header has been set to accept the http://siteang.azurewebsites.net site that is making the call:

 [System.Web.Http.HttpGet]
    [EnableCors(origins: "http://siteang.azurewebsites.net", headers: "*", methods: "*")]
    public ViewItemModel GetComparisons([FromUri] ComparisonRequestModel comparisonModel)
    {
        return _callAndSearchApis.SearchApis(comparisonModel);
    }

Any help in determing why this request is being rejected by the WebApi controller will be much appreciated.

like image 302
user1352057 Avatar asked Sep 20 '16 19:09

user1352057


3 Answers

CORS request headers are imposed by the browser automatically for cross origin requests. There's no way to change them. In fact, CORS would be pointless if the client could set CORS allow headers.

The error your seeing is that your server didn't include the required Access-Control-Allow-* headers in the response during a preflight request. Preflight requests (OPTIONS) are performed when the client is doing something other than a simple GET request, including when custom request headers are added (which your Allow headers are).

To be fair, your confusion is probably not helped by the error ("... not present on the requested resource").

I'd recommend removing the CORS headers from the request and trying it again. If it still fails, capture the request using an HTTP proxy like Fiddler and update your question with the CORS headers in the preflight request and response.

like image 76
Richard Szalay Avatar answered Nov 07 '22 17:11

Richard Szalay


Firstly, you are mixing protocols here http and https. Check the url you are requesting is having https. Please make sure that is correct first. Then you need to figure out if the server is rejecting and what it is doing. There are number of resources for Enabling cors. Even Stackoverflow has numberof threads.

https://stackoverflow.com/search?q=Enabling+Cors+WebApi

http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Edited Answer: Sometimes your IIS would interfere with the preflight OPTIONS requests. Try doing something like this in your web.config and see if it works.

http://benfoster.io/blog/aspnet-webapi-cors

like image 40
Prasanth Nittala Avatar answered Nov 07 '22 17:11

Prasanth Nittala


It's likely that your server is returning a 500 error, and that it is that 500 error response itself that does not have CORS headers enabled on it. To confirm, I would encourage you to use a tool like Postman to test your API directly and ensure that the actual API request completes successfully.

Separately, you can then consider whether you want various server status response messages (for 500, 403, 302, etc) to have CORS headers included with them.

like image 43
JcT Avatar answered Nov 07 '22 15:11

JcT