如何为 CORS 配置 Azure API 管理

问题描述 投票:0回答:4

我已经创建了 Azure API 管理服务并连接了我的 API。我向其中添加了

CORS
政策。

我检查了计算有效政策,结果是这个政策

<policies>
    <inbound>
        <!-- base: Begin Product scope -->
        <!-- base: Begin Global scope -->
        <cors allow-credentials="true">
            <allowed-origins>
                <origin>https://developer.mydomain.com</origin>
            </allowed-origins>
            <allowed-methods preflight-result-max-age="300">
                <method>*</method>
            </allowed-methods>
            <allowed-headers>
                <header>*</header>
            </allowed-headers>
            <expose-headers>
                <header>*</header>
            </expose-headers>
        </cors>
        <!-- base: End Global scope -->
        <!-- base: End Product scope -->
        <cors>
            <allowed-origins>
                <origin>*</origin>
            </allowed-origins>
            <allowed-methods>
                <method>GET</method>
                <method>POST</method>
            </allowed-methods>
        </cors>
    </inbound>
    <backend>
        <!-- base: Begin Product scope -->
        <!-- base: Begin Global scope -->
        <forward-request />
        <!-- base: End Global scope -->
        <!-- base: End Product scope -->
    </backend>
    <outbound />
    <on-error />
</policies>

如果我用 C# 调用 API,它就可以工作。然后,我创建了一个简单的 JavaScript 来调用 API,但无法避免

CORS
。我尝试了不同的 JavaScript

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    </head>
    <body>
        <script>
        var url = '';
        var headerKey = 'subscription-Key';
        var headerValue = 'e1e21';

        $.ajax({
            url: url,
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Origin","https://www.puresourcecode.com/");
                xhrObj.setRequestHeader("Access-Control-Allow-Origin","https://www.puresourcecode.com/");
                xhrObj.setRequestHeader("Access-Control-Request-Method","GET");
                xhrObj.setRequestHeader("Access-Control-Allow-Credentials","true");
                xhrObj.setRequestHeader("Access-Control-Request-Headers","X-Custom-Header");
                xhrObj.setRequestHeader("Access-Control-Allow-Headers","Origin, Content-Type, Accept, Authorization, X-Request-With");
                xhrObj.setRequestHeader(headerKey,headerValue);
            },
            type: "GET",
            contentType: "application/json; charset=utf-8",
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function() {
            alert("error");
        });

        // jQuery preflight request
        $.ajax({
            type: "GET",
            headers: {headerKey: headerValue},
            url: url
        }).done(function (data) {
            console.log(data);
        });
        
        // XMLHttpRequest preflight request
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.setRequestHeader(headerKey, headerValue);
        xhr.onload = function () {
            console.log(xhr.responseText);
        };
        xhr.send();
        
        // Fetch preflight request
        var myHeaders = new Headers();
        myHeaders.append(headerKey, headerValue);
        fetch(url, {
            headers: myHeaders
        }).then(function (response) {
            return response.json();
        }).then(function (json) {
            console.log(json);
        });
        </script>
    </body>
</html>

他们所有人都因为

CORS
而失败。我尝试添加
preflight-result-max-age="300"
并指定了
allowed-headers
就像我用来传递订阅密钥但没有成功的那样。我也尝试将此文件复制到我的服务器中,但出现相同的错误。

作为

origin
,我设置了
*
,因为我认为这样每个URL的每个请求都会被接受,但显然不会。

在 Azure API 管理中应用什么正确设置可以避免

CORS

azure cors azure-api-management
4个回答
13
投票

我认为当您启用

Developer portal
时就会出现问题。然后,在门户的配置中,启用
CORS
。此时,Azure 会自动向
API Management Service
添加全局策略,但你并不知道。

<policies>
    <inbound>
        <!-- base: Begin Global scope -->
        <cors allow-credentials="true">
            <allowed-origins>
                <origin>https://developer.mydomain.com</origin>
            </allowed-origins>
            <allowed-methods preflight-result-max-age="300">
                <method>*</method>
            </allowed-methods>
            <allowed-headers>
                <header>*</header>
            </allowed-headers>
            <expose-headers>
                <header>*</header>
            </expose-headers>
        </cors>
        <!-- base: End Global scope -->
    </inbound>
</policies>

令人高兴的是,您在 API 中配置了

CORS
,当您尝试从 JavaScript 调用它们时,您将面临
CORS
错误。

如果您在 Azure 门户中打开

CORS
配置,您可以看到类似的内容:

<policies>
    <inbound>
        <base />
        <cors>
            <allowed-origins>
                <origin>*</origin>
            </allowed-origins>
            <allowed-methods preflight-result-max-age="300">
                <method>GET</method>
                <method>POST</method>
            </allowed-methods>
            <allowed-headers>
                <header>*</header>
                <header />
            </allowed-headers>
            <expose-headers>
                <header>*</header>
            </expose-headers>
        </cors>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

我的理解是门户将基本配置与您的相结合。因此,就像

Active Directory
中一样,正在应用更严格的政策。这意味着在我的示例中,只有
Developer Portal
可以调用 API,而不会出现
CORS
问题。

解决方案

删除

<base />
下的
<inbound>
并保存。


7
投票

界面截图

我在设置的每个 API 管理上都遇到了同样的问题。我总是忘记我做了什么来解决它,所以这也是对未来的我的一个提醒。

  • 添加 CORS 策略,
  • 允许的标头 *
  • 启用允许凭据
  • 在 URL 中包含斜线


3
投票

是的,在全局设置中更新 CORS 解决了我们的问题。我们花费了大量时间通过覆盖特定服务的策略来确定根本原因来进行故障排除。事实证明,我们必须在全局层面应用 CORS 政策。API Management Service -> APIS -> 所有 APIS -> 入站处理设置


0
投票

我认为问题不在于在子级或根级应用该政策。当我在多个级别应用该策略时,就会出现此问题

© www.soinside.com 2019 - 2024. All rights reserved.