Web Api 2 Preflight CORS request for Bearer Token

FancyNancy picture FancyNancy · Nov 17, 2014 · Viewed 11.1k times · Source

I have a web-app with an AngularJS front-end and a Web Api 2 back-end, and it uses bearer-tokens for authentication.

All is well in FireFox & IE, but with Chrome, my initial login request is SOMETIMES pre-flighted.

Here's the call from the AngularJS service:

$http.post(http://localhost:55483/token, data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) { ... });

The preflight request gets kicked back with an "Allow-Access-Control-Origin" error.

However, if I click the Login button again (thereby re-sending the above request) all is well.

Any idea on how to prevent/trap/handle this?

PS: I use the LOC

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

in the ApplicationOAuthProvider.cs file to put the CORS allow-header on the /Token request, which works fine in IE, FireFox and sometimes in Chrome.

Answer

Steve Lam picture Steve Lam · Oct 17, 2015

The below is Fancy comment:

Figured this out with help from post by LeftyX on Jun 29:
- Move this LOC app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); to the FIRST LINE in the ConfigureAuth method of Startup.Auth.cs.
- Then, REMOVE this LOC context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); from the GrantResourceOwnerCredentials() method of ApplicationOAuthProvide.cs.

Preflight CORS-request them gets handled properly, and then the actual requet goes through


Thank man, you save my whole day.
Cause it happens for many guys, I bring your comment to answer box for other guys can see it.

I don't want to get vote up for this. Please comment on my answer instead

Thank you