2

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:

  1. As mentioned above I'm not having CORS issues with any of the /api calls
  2. When I enter the correct credentials the call is "successful" (i.e. Status Code 200 but 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.

1 Answer 1

1

Okay so I've finally found the reason why this was happening. As highlighted in here it seems that the /token endpoint is initialised before the WebApiConfig is and so any set up here would not enable CORS for the /token endpoint.

To enable it for this endpoint as well the following should be added in the IdentityConfig.cs Create function:

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{

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

    ...

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.