disable anonymous authentication in IIS if you do not need it.
Add this to your global asax:
protected void Application_BeginRequest(object sender, EventArgs e) { if ((Context.Request.Path.Contains("api/") || Context.Request.Path.Contains("odata/")) && Context.Request.HttpMethod == "OPTIONS") { Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]); Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); Context.Response.AddHeader("Access-Control-Allow-Credentials", "true"); Context.Response.End(); } }
Make sure that when you enable cors, you also enable the use of credentials, for example:
public static void Register(HttpConfiguration config) { // Web API configuration and services var cors = new EnableCorsAttribute("*", "*", "*"); cors.SupportsCredentials = true; config.EnableCors(cors); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
As you can see, I enable CORS globally and using the BeginRequest hook application, I authenticate all OPTIONS requests for api (Web Api) and odata requests (if you use it).
This works great with all browsers; on the client side, remember to add xhrFiled withCredentials, as shown below.
$.ajax({ type : method, url : apiUrl, dataType : "json", xhrFields: { withCredentials: true }, async : true, crossDomain : true, contentType : "application/json", data: data ? JSON.stringify(data) : '' }).....
I am trying to find another solution, avoiding using a hook, but without success so far, I would use the web.config configuration to do something like the following: WARNING CONFIGURATION DOES NOT WORK BELOW!
<system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> <authentication mode="Windows" /> <authorization> <deny verbs="GET,PUT,POST" users="?" /> <allow verbs="OPTIONS" users="?"/> </authorization> </system.web> <location path="api"> <system.web> <authorization> <allow users="?"/> </authorization> </system.web> </location>