0
votes

I have a webapi which is configured to use WINDOWS AUTHENTICATION.

var cors = new EnableCorsAttribute(origen, "*", "*") { SupportsCredentials = true };
            config.EnableCors(cors);

In my angular app I have the follwing methods:

GET methods work perfect.

result.CargarAreas = function (callBack, onError) {

        //url = WebApi + "Personas";
        var url = constants.apiPath + "Areas";

        //$http.get(url, { headers: { "Access-Control-Allow-Origin": constants.serverPath } })
        $http.get(url, {
            withCredentials: true
        })
        .then(function (data) {
            callBack(data);
        })
        .catch(function (data) {
            onError(data);
        });
    };

POST methods give me this error:

result.GuardarContacto = function (callBack, onError, data) {

        //url = WebApi + "Contactos";
        var url = constants.apiPath + "Contactos";

        $http.post(url, data, { headers: { "Access-Control-Allow-Origin": constants.serverPath } })

        .then(function (data) {
            callBack(data);
        })
        .catch(function (data) {
            onError(data);
        });
    };

and finally the web api method

[HttpGet]
        [Route("api/AutenticationSite")]
        public IHttpActionResult AutenticationSite()
        {
            string user = HttpContext.Current.Request.LogonUserIdentity.Name.ToString();
            string[] subUser = user.Split('\\');
            bool respuesta = UsuariosDao.Authorize(subUser[1]);

            if (respuesta == true)
            {
                return Ok("Authenticated: " + user);
            }
            else
            {
                return BadRequest("Not authenticated" );
            }
        }

and the DAMN error we have been fighting for hours:

XMLHttpRequest cannot load http://a.b.com/api/Contactos. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://a.b.com' is therefore not allowed access. The response had HTTP status code 401.

UPDATE 1

Info about the request and response

Request URL:http://a.b.com/api/Contactos Request Method:OPTIONS Status Code:200 OK Remote Address:181.143.YY.XX:80 Referrer Policy:no-referrer-when-downgrade Response Headers (11) Request Headers view source Accept:/ Accept-Encoding:gzip, deflate, sdch Accept-Language:es-ES,es;q=0.8 Access-Control-Request-Headers:content-type Access-Control-Request-Method:POST Cache-Control:no-cache Connection:keep-alive Host:a.b.com Origin:http://a.b.com Pragma:no-cache Referer:http://a.b.com/Index.html User-Agent:Mozilla/5.0 (Windows NT 10.0

enter image description here

1
$http.post(url, data, { headers: { "Access-Control-Allow-Origin" are you setting Access-Control-Allow-Origin in the request header? that's not how CORS access is granted - the server must respond with a Access-Control-Allow-Origin ... setting such a header in the request will trigger a pre-flight OPTIONS request, which needs to be handled by the server correctly for CORS to work ... notice how GET works, because you aren't sending a "non-standard" header in the request - Jaromanda X
I just removed it and still get the same problem - Luis Valencia
check the request in the developer tools network tab - look the request headers, response headers, request type (is it still preflighting an OPTIONS request) - Jaromanda X
@LuisValencia-MVP check what you got for Access-Control-Allow-Origin Header in developer tools -> network tab -> headers. I think you may need [EnableCors] attribute on right above on your function - Sankar
It does not return Access-Control-Allow-Origin in response, But it should. Have you gone through this? docs.microsoft.com/en-us/aspnet/web-api/overview/security/… - Sankar

1 Answers

0
votes

Remove access-control header setting in your angular code. Looks like you have this header getting set at multiple places and thus the output is having none, despite your web api code enabling cors.

Look out for

  • web.config => httpRuntime => httpHandlers => header getting set
  • Usage of MVC.CORS NuGet 'instead' of WebAPI.CORS package. Here your need to use the WebAPI one (although it depends on MVC one so don't uninstall it)
  • No need to change the OPTIONS verb handler in global.asax
  • Multiple calls to config.EnableCors in different places (global.asax and webapi.config). Search across your source for 'cors' just to be sure on this.
  • Check if the attribute is set on a global level or controller/action level. It may be that your specific action is getting excluded. Try doing a post on some other controller to be sure
  • Variable 'origen' correctly stores the client's IP address and port. Any deviation will lead to not sending header. Try using star * rather than specific client to test.