Enable CORS for Web Api 2 and OWIN token authentication

I know your issue was solved inside comments, but I believe is important to understand what was causing it and how to resolve this entire class of problems.

Looking at your code I can see you are setting the Access-Control-Allow-Origin header more than once for the Token endpoint:

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

And inside GrantResourceOwnerCredentials method:

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

This, looking at the CORS specifications, is itself an issue because:

If the response includes zero or more than one Access-Control-Allow-Origin header values, return fail and terminate this algorithm.

In your scenario, the framework is setting this header two times, and understanding how CORS must be implemented, this will result in the header removed in certain circumstances (possibly client-related).

This is also confirmed by the following question answer: Duplicate Access-Control-Allow-Origin: * causing COR error?

For this reason moving the call to app.UseCors after the call to ConfigureOAuth allows your CORS header to be set only once (because the owin pipeline is interrupted at the OAuth middleware, and never reaches the Microsoft CORS middleware for the Token endpoint) and makes your Ajax call working.

For a better and global solution you may try to put again app.UseCors before the OAuth middleware call, and remove the second Access-Control-Allow-Origin insertion inside GrantResourceOwnerCredentials.

Leave a Comment