Notes about CORS implementation in Web API. 

We’ve created CORS interface using the article
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors
A few points,t hat I want to highlight:
  1. DisableCors doesn’t stop server to send response, it just sends response without Access-Control-Allow-Origin header.
It’s browser responsibility to check response and generate an error.
It’s important to understand that same-origin policy does not prevent the browser from sending the request. Instead, it prevents the application from seeing the response
  1. When cookies allowed to be shared between sub domains of the same domain, “same origin policy” consider sub domains as different origins.
There is no partial wild cards supported in origins, such as all sub domains *.example.com.
If the server allows the request, it sets the Access-Control-Allow-Origin header. The value of this header either matches the Origin header, or is the wildcard value “*”, meaning that any origin is allowed.
I’ve submitted enhancement suggestion to MS at https://connect.microsoft.com/VisualStudio/feedback/details/2703507/web-api-support-partial-wild-cards-in-cors-origins-field, but it can be done as custom policy implementation as it was answered at http://forums.asp.net/post/6050160.aspx
     3.  Out of the box implementation in attributes use hard coded Origins, with note in documentation:
For example, a custom CORS policy provider could read the settings from a configuration file.
MS should  supply input from configuration out of the box. One of examples provided  in MSDN blog https://blogs.msdn.microsoft.com/webdev/2013/07/02/manage-cors-policy-dynamically/.
Better implementation posted at http://jnye.co/Posts/2032/dynamic-cors-origins-from-appsettings-using-web-api-2-2-cross-origin-support
  1. If you want to share cookies, you need to enable Credentials on both client and server.
Credentials include cookies as well as HTTP authentication schemes. To send credentials with a cross-origin request, the client must set XMLHttpRequest.withCredentials to true.
$.ajax({
    type: 'get',
    url: 'http://www.example.com/api/test',
    xhrFields: {
        withCredentials: true
    }
[EnableCors(origins: “http://myclient.azurewebsites.net”, headers: “*”, methods: “*”, SupportsCredentials = true)]
Further reading:
Advertisements