0

For reference I'm using Windows 10 and Visual Studio 2017.

I have an MVC web api and corresponding web application complete with login capabilities. I'm simply attempting to debug using IE. Whenever I use a GET call I'm met with the following error: SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied. I have CORS configured and enabled so I'm at a complete loss as to why this isn't working.

In my WebApiConfig file I have this:

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.EnableCors();
    }

And then in the Web.config file I have this:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="http://localhost:53942" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
</httpProtocol>

The call itself is being made using this code:

var returnValue = [];
    console.log(localStorage.getItem('accessToken'));
    jQuery.support.cors = true;
    if (window.XMLHttpRequest) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", 'http://localhost:60690/api/ProfilePicture?Username=' + username, false);
        xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
        xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('accessToken'));
        xmlhttp.send();
        if (xmlhttp.status == 200) {
            returnValue = jQuery.parseJSON(xmlhttp.responseText);
        }
    }
    return returnValue;

Again, I'm just trying to debug. When the projects are deployed they're going to be on the same domain so CORS is irrelevant. What am I missing?

Rhendar
  • 410
  • 7
  • 25
  • You could try to replace `` by `` – greyxit Feb 12 '18 at 16:40
  • @JimmyFL I had that originally but apparently you cannot have and as they conflict with one another. – Rhendar Feb 12 '18 at 16:43
  • What ports are your API and UI projects running on? –  Feb 12 '18 at 18:22
  • The API is on http://localhost:60690/ and the UI is on http://localhost:53942/ – Rhendar Feb 12 '18 at 18:23
  • Ordinarily you would configure CORS in code, not through the custom headers collection. Also make sure you remove the HTTP handler that removes OPTIONS requests. Search your API config file for `OPTIONSVerbHandler` –  Feb 12 '18 at 18:25
  • Second, open Fiddler and inspect the *actual* web traffic. Make sure your browser is issuing the OPTIONS requests, and make sure the response contains the `Access-Control-***` headers. –  Feb 12 '18 at 18:26
  • Third, you are checking the status of your request outside of a callback. The status will never be 200 there. Only check for the status inside a callback function. –  Feb 12 '18 at 18:31
  • Okay, I commented out the OPTIONSVerbHandler part but I don't think anything changed. Do you happen to know of a good guide for setting up CORS? – Rhendar Feb 12 '18 at 18:32
  • Firefox and Chrome do not support CORS for localhost. You'll have to add a plugin for that, or alternately, there are command-line switches that disable all kinds of security including that restriction. Should be easy to find with Google. – McGuireV10 Feb 12 '18 at 20:47
  • I'm debugging in IE. – Rhendar Feb 12 '18 at 20:52
  • Chrome supports CORS for localhost. I run my website on localhost with CORS every day without a browser extension. –  Feb 12 '18 at 20:52

1 Answers1

1

Alright, I finally figured this out. Here's what I did:

  1. In the Web.config file remove the CustomHeader part. Get rid of it all.
  2. Found this other StackOverflow question: CORS on OWIN and accessing /token causes 'Access-Control-Allow-Origin' error. Ironically the answer with the most downvotes was the one that helped me the most. I added in the following line into the GrantResourceOwnerCredentials class:

    context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

  3. Go into each controller and add the following line at the top:

    [EnableCors(origins: "http://localhost:53942", headers: "", methods: "", SupportsCredentials = true)]

Once I did this it started working.

Rhendar
  • 410
  • 7
  • 25