MSDN article on CORS in Web API 2
December 3, 2013
My MSDN article on CORS in Web API is now out!
Given the nature of CORS, I really wanted to spend much of the article explaining CORS by itself. With that understanding then it’s simple enough to understand how Web API surfaces support for CORS.
Enjoy.
6 Comments
leave one →
Reblogged this on http://www.leastprivilege.com.
Enjoyed your article in MSDN magazine and online. Good overview of CORS.
thx
Good article on CORS and it helped to me get started and understand the basics. I am getting error “redirects are not allowed for cors preflight requests”. The response code is 302 because the call is redirected to ACS authorization server. Is redirects supported in CORS?
Right — your preflight request is hitting some code in your app that returns 401, and the WIF code is then converting that to 302 to ACS. I suspect you have the global deny authorization rule in web.config that’s doing it.
Brock:
This was very frustrating indeed, because IE 11 seems to ignore it (at least on my dev box) and works properly, but no other browser worked and had an error on /Token
Because /Token is an OWIN Service and not a Controller
The Microsoft.Owin.Cors, System.Web.Cors Modules will conflict if you try to set them both globally. So, to enable Owin.Cors for just the /Token endpoint here is a working solution that I place in the top of Startup:ConfigureAuth.
Adjust your CorsPolicy appropriately as this allows anything to try to use /Token…
I know for a fact the VB version works as I am using it, I translated to C# in my head so YMMV.
‘VB Version (requires Imports for Microsoft.Owin.Cors, System.Web.Cors, System.Threading.Tasks)
‘Enable OWIN.Cors support ONLY on the /Token Service.
Dim tokenCorsPolicy = New CorsPolicy With {.AllowAnyHeader = True, .AllowAnyMethod = True, .AllowAnyOrigin = True}
Dim corsOptions = New CorsOptions With {.PolicyProvider = New CorsPolicyProvider With {.PolicyResolver = Function(request) Task.FromResult(If(request.Path.ToString.ToLower = “/token”, tokenCorsPolicy, Nothing))}}
app.UseCors(corsOptions)
//C# version (requires using for Microsoft.Owin.Cors, System.Web.Cors, System.Threading.Tasks)
//Enable OWIN.Cors support ONLY on the /Token Service.
var tokenCorsPolicy = new CorsPolicy {AllowAnyHeader = true, AllowAnyMethod = true, AllowAnyOrigin = true};
var corsOptions = new CorsOptions {PolicyProvider = new CorsPolicyProvider {PolicyResolver = (request) => Task.FromResult((request.Path.ToString.ToLower == “/token”) ? tokenCorsPolicy : null))}}
app.UseCors(corsOptions);