Search code examples
javascriptiisxmlhttprequestweb-config

Access-Control-Allow-Origin for http & https


Following javascript XMLHttpRequest is working when accessing the site with https:

var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://site/api/status", true);
xhttp.withCredentials = true;
xhttp.send();

The web.config for the requested site is the following:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                    <add name="Access-Control-Allow-Origin" value="https://intranet.company.local" />
                    <add name="Access-Control-Allow-Credentials" value="true" />
                    <add name="Access-Control-Allow-Headers" value="Content-Type,Cache-Control,Pragma,Expires,Authorization" />
                    <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

It should now also be possible to use the site with http also it is not secure. It is working if I change the XMLHttpRequest URL to "http://site/api/status" and the Access-Control-Allow-Origin to "http://intranet.company.local".

It is also not a problem to change the XMLHttpRequest URL based on the given protocol, but I cannot find a working web.config configuration to allow both protocols as the wildcard value for Access-Control-Allow-Origin is not working when using credentials.


Solution

  • Thansk to @Jaromanda X for the help. I used his reference from the iis cors module (Link) to solve the problem:

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <system.webServer>
            <cors enabled="true" failUnlistedOrigins="true">
                <add origin="*" allowed="false"/>
                <add origin="https://intranet.company.local" allowCredentials="true"> 
                    <allowHeaders allowAllRequestedHeaders="true" />
                    <allowMethods>
                         <add method="GET" />
                    </allowMethods>
                </add>
                <add origin="http://intranet.company.local" allowCredentials="true">
                    <allowHeaders allowAllRequestedHeaders="true" />
                    <allowMethods>
                         <add method="GET" />
                    </allowMethods>
                </add>
            </cors>
        </system.webServer>
    </configuration>