Wednesday, January 15

Cross Origin Resource Sharing (CORS) in ASP.net Web API

The Same-Origin policy is a security policy enforced on client-side web apps to prevent interactions between resources from different origins. This is useful for preventing malicious behavior such as XSS (Cross Site Scripting) attacks. This measure prevents interactions between known resources. Cross-origin resource sharing (CORS) is a mechanism that allows JavaScript on a web page to make XMLHttpRequests to another domain, not the domain the JavaScript originated. CORS specifications allow us to make cross origin AJAX calls. ASP.net Web API supports CORS.

With ASP.NET Web API, CORS can be enabled at application level or at specific controller or action level. To make it enable globally, add “Access content allow origin” to web.config file:
<system.webserver>
    <httpprotocol>
      <customheaders>
        <add name="Access-Control-Allow-Origin" value="*"></add>
      </customheaders>
    </httpprotocol>
  </system.webserver>
To enable CORS at Controller level or at action level, add config.EnableCors to Register method of WebApiConfig.cs file.

using System.Web.Http.Cors;

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
               //CORS enabled
        config.EnableCors();
    }
}

To enable CORS for a specific Controller, add  [EnableCors] for that controller.

 [EnableCors(origins: "*", headers: "*", methods: "*")]
public class TestController : ApiController
{
    public HttpResponseMessage Get() { ... }
    public HttpResponseMessage Get(int id) { ... }

    [DisableCors]
    public HttpResponseMessage Post() { ... }
}

To restrict domain, we can supply a list of domain name in origin parameter.
 [EnableCors(
               origins: "http://web1.com,http://web2.com",
               headers: "accept,content-type,origin",
               methods: "get,post")]
public class TestController : ApiController
{
               public HttpResponseMessage Get() { ... }
               public HttpResponseMessage Post() { ... }
               public HttpResponseMessage Put() { ... }
}

No comments:

Post a Comment