http 和 https 的访问控制允许来源

Access-Control-Allow-Origin for http & https

以下 javascript XMLHttpRequest 在使用 https 访问站点时有效:

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

请求站点的 web.config 如下:

<?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>

现在应该也可以使用带有 http 的站点,但它不安全。如果我将 XMLHttpRequest URL 更改为“http://site/api/status”并将 Access-Control-Allow-Origin 更改为“http://intranet.company.local”。

根据给定的协议更改 XMLHttpRequest URL 也不是问题,但我找不到有效的 web.config 配置来允许这两种协议作为访问控制的通配符值-Allow-Origin 在使用凭据时不起作用。

感谢@Jaromanda X 的帮助。我使用了他在 iis cors 模块中的引用 (Link) 解决问题:

<?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>