I'm working on an Angular 2 application that is making service calls to an ASP.NET Web API 2 service. In this service CORS has been enabled in the WebApiConfig like so:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
...
}
}
This has been working fine and I've hadn't had any problems with CORS. For example calling /api/users retrieves all the users successfully.
Now however I'm trying to use the .NET Identity Token for the login functionality which is giving me issues related to CORS. When calling the /token to perform a login in my login.service.ts:
loginUser(username: string, password: string) {
let serviceURL = 'http://myurl/token';
let body = 'username=' + username + '&password=' + password + '&grant_type=password';
let headers: Headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options: RequestOptions = new RequestOptions({
headers: headers
});
return this.http.post(serviceURL, body, options)
.map(res => this.extractData(res))
.catch(this.handleError);
}
I get the following error:
XMLHttpRequest cannot load http://myurl/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 400.
I'm finding this confusing for two reasons:
- As mentioned above I'm not having CORS issues with any of the
/apicalls - When I enter the correct credentials the call is "successful" (i.e.
Status Code 200but I get the error listed above.
I've looked at a lot of different articles with a similar implementation and I can't seem to find what's wrong with mine.