How to make CORS Authentication in WebAPI 2?
Solution 1:
Look at what I have found!
Add in some custom headers inside <system.webServer>
.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
</customHeaders>
</httpProtocol>
Then I can do the CORS authentication.
Solution 2:
I had many trial-and-errors to setup it for AngularJS-based web client.
For me, below approaches works with ASP.NET WebApi 2.2 and OAuth-based service.
- Install
Microsoft.AspNet.WebApi.Cors
nuget package. - Install
Microsoft.Owin.Cors
nuget package. - Add
config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE"));
to the above ofWebApiConfig.Register(config);
line at Startup.cs file. - Add
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
to the Startup.Auth.cs file. This must be done prior to callingIAppBuilder.UseWebApi
- Remove any xml settings what Blaise did.
I found many setup variations and combinations at here stackoverflow or blog articles. So, Blaise's approach may or may not be wrong. It's just another settings I think.
Solution 3:
After many hours of searching and looking at many many different solutions to this i have managed to get this working as per the below.
There are a number of reasons this is happening. Most likely you have CORS enabled in the wrong place or it is enabled twice or not at all.
If you are using Web API and Owin Token end point then you need to remove all the references to CORS in your Web API method and add the correct owin method because web api cors will not work with Token endpoint whilst Owin cors will work for both Web API and Token auth end points so lets begin:
Make sure you have the Owin Cors package installed Remove any line that you have eg.config.EnableCors(); from your WebAPIconfig.cs file
-
Go to your startup.cs file and make sure you execute Owin Cors before any of the other configuration runs.
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); ConfigureAuth(app);
If your still having problems go to: Startup.Auth.cs and ensure you have the following in your ConfigureAuth method (you shouldnt need this if your startup.cs file is correct)
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);