For reference I'm using Visual Studio 2017 and Windows 10.
I have an MVC webapi project designed using a template provided by Visual Studio with accounts that are stored in an SQL database. I have another project which is the website itself that the users log into. I'm attempting to debug in VS but am being met with an access is denied error message whenever a GET request is made outside of the initial login. I've enabled CORS on the webapi but it didn't seem to make much of a difference.
Here's how I enabled CORS.
In the WebAPIConfig file I have the following:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
// 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 }
);
}
}
And then in the Web.config file I have this:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<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>
This is the code from the website making the call:
function getProfilePicture(username){
var returnValue = [];
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;
}
The error message says "SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied."
Did I not properly enable CORS?
Update
I downloaded Postman in an attempt to figure out the issue. I'm actually able to make GET calls with Postman without any errors. It's returning the data and everything. One thing I did notice is it doesn't look like the Authorization header is actually being sent. It's missing from the data in Fiddler.
Specifying Access-Control-Allow-Credentials: true
as a response header is incompatible with Access-Control-Allow-Origin: *
. If you're going to use credentials, you must use Access-Control-Allow-Origin: <value-of-origin-request-header>
.
User contributions licensed under CC BY-SA 3.0