How to make CORS Authentication in WebAPI 2?

Blaise picture Blaise · Nov 19, 2013 · Viewed 84.7k times · Source

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?

Answer

Blaise picture Blaise · Nov 19, 2013

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.