Search code examples
asp.netiiscorsweb-config

Access-control-allow-origin with multiple domains


In my web.config I would like to specify more than one domain for the access-control-allow-origin directive. I don't want to use *. I've tried this syntax:

<add name="Access-Control-Allow-Origin" value="http://localhost:1506, http://localhost:1502" />

this one

<add name="Access-Control-Allow-Origin" value="http://localhost:1506 http://localhost:1502" />

this one

<add name="Access-Control-Allow-Origin" value="http://localhost:1506; http://localhost:1502" />

and this one

<add name="Access-Control-Allow-Origin" value="http://localhost:1506" />
<add name="Access-Control-Allow-Origin" value="http://localhost:1502" />

but none of them work. What is the correct syntax ?


Solution

  • There can only be one Access-Control-Allow-Origin response header, and that header can only have one origin value. Therefore, in order to get this to work, you need to have some code that:

    1. Grabs the Origin request header.
    2. Checks if the origin value is one of the whitelisted values.
    3. If it is valid, sets the Access-Control-Allow-Origin header with that value.

    I don't think there's any way to do this solely through the web.config.

    if (ValidateRequest()) {
        Response.Headers.Remove("Access-Control-Allow-Origin");
        Response.AddHeader("Access-Control-Allow-Origin", Request.UrlReferrer.GetLeftPart(UriPartial.Authority));
    
        Response.Headers.Remove("Access-Control-Allow-Credentials");
        Response.AddHeader("Access-Control-Allow-Credentials", "true");
    
        Response.Headers.Remove("Access-Control-Allow-Methods");
        Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    }