Search code examples
asp.net-mvccorstoken

Enable CORS for ASP API Token request


I have a project that has both an API and an Area that contains some web forms.
Recently the Token endpoint of the API started throwing CORS errors and I can't figure out why or how to fix it.

I've updated the Startup.Auth.cs file with:app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

Also tried adding config.EnableCors(new EnableCorsAttribute("*", "*", "GET,POST")); to the WebApiConfig.cs file.

Neither of these have added the 'Access-Control-Allow-Origin' header that is needed. (I do get a different error if both of these are implemented at the same time, so I know that is not the issue.)

Is there another location in the project that I need to set to allow CORS requests for an auth token?


Solution

  • Okay, found the problem(s).

    First, my test harness was pointing at the wrong location so any changes I was making were having no effect and my break points were not being hit. My bad.

    Second, the configuration that finally got me working is to have the following code:

    ApplicationOAuthProvider.GrantResourceOwnerCredentials:
    var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
    if (allowedOrigin == null) allowedOrigin = "*";
    
    
    WebApiConfig.Register:
    config.EnableCors(new EnableCorsAttribute("*", "*", "GET,POST"));
    

    I hope this helps anyone else that is struggling with CORS and Katana/OWIN middleware.