Restrict WebApi endpoints using CORS

Viewed 13

I have created a WebApiApplication project.

In my WebApiConfig.cs my register method looks like this -

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var json = config.Formatters.JsonFormatter;

        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

        json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        config.Formatters.Remove(config.Formatters.XmlFormatter);

        string origins = GetAllowedOrigins();
        var cors = new EnableCorsAttribute(origins, "*", "*");
        config.EnableCors(cors);

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "ActionApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

And then try to restrict all requests by adding -

    private static string GetAllowedOrigins()
    {
        return "http://www.example.com";
    }

I cannot understand why but when I deploy my api to my hosting server, ALL requests to the endpoints, regardless of where they come from are allowed.

I tried a different route (removing my previous change) and editing the web.config by adding -

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="http://www.example.com" />
  </customHeaders>
</httpProtocol>

Again any requests from my local machine were accepted even though they were not from "http://www.example.com".

The last thing I tried was adding the following to my controller -

[EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]
public class MyController : ApiController

However again, all requests were accepted. My understanding is if I specifically define the origin URLs then all others should fail, where am I going wrong?

0 Answers
Related