The scenario is simple, I need to log in from another server (different from the API server) to retrieve the access token.
I installed Microsoft.Owin.Cors
package on the API Server. In Startup.Auth.cs
file, under public void ConfigureAuth(IAppBuilder app)
, I added in
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
In WebApiConfig.cs
, under public static void Register(HttpConfiguration config)
, I added in these lines:
// Cors var cors = new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS"); config.EnableCors(cors);
What else should I change?
You can enable CORS per action, per controller, or globally for all Web API controllers in your application. To enable CORS for a single action, set the [EnableCors] attribute on the action method.
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.
In Web API, content negotiation is performed by the runtime (at the server side) to determine the media type formatter to be used based to return the response for an incoming request from the client side. Content negotiation is centered on Media type and Media type formatter.
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.
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.
Microsoft.AspNet.WebApi.Cors
nuget package.Microsoft.Owin.Cors
nuget package.config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE"));
to the above of WebApiConfig.Register(config);
line at Startup.cs file. app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
to the Startup.Auth.cs file. This must be done prior to calling IAppBuilder.UseWebApi
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With