【问题标题】:Azure Function called from Azure API Management CORS Error从 Azure API 管理 CORS 错误调用的 Azure 函数
【发布时间】:2021-10-25 11:39:38
【问题描述】:

我创建了一个简单的 HTTP Trigger 函数并将其链接到 API 管理

然后我在 API 管理 中设置了 Cors 政策,如下所示:

<policies>
<inbound>
    <cors>
        <allowed-origins>
            <origin>*</origin>
        </allowed-origins>
        <allowed-methods>
            <method>*</method>
        </allowed-methods>
    </cors>
</inbound>
<backend>
    <forward-request />
</backend>
<outbound />
<on-error />

当我从 blazor wasm 调用它时,它会给出以下错误:

Access to fetch at 'https://example-api.azure-api.net/teste/Teste' from origin 'https://localhost:5001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

需要注意的几点:

  • 当我直接从浏览器调用“https://example-api/teste/Teste”时,它可以工作。
  • 当我直接从 blazor wasm 调用函数时(没有 API 管理),它可以工作。
  • 当我从 blazor wasm 调用“https://example-api/teste/Teste”时,它给出了提到的 Cors 错误

有什么想法吗?

【问题讨论】:

    标签: azure azure-functions azure-api-management


    【解决方案1】:

    首先注册 Azure AD 以保护 Azure 功能,然后

    1. 配置重定向 URI。选择Web并输入&lt;app-url&gt;/.auth/login/aad/callback

    2. 启用隐式授权流程 > 定义 API 范围并复制它

    3. 配置 API 权限。让您的客户端应用程序具有访问功能的权限

    • 在您的应用服务应用中启用 Azure Active Directory
    • 在 Azure Function 中配置 CORS 策略

    代码

    1. 创建自定义AuthorizationMessageHandler
    using Microsoft.AspNetCore.Components;
    using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
    
    public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler
    {
        public CustomAuthorizationMessageHandler(IAccessTokenProvider provider, 
            NavigationManager navigationManager)
            : base(provider, navigationManager)
        {
            ConfigureHandler(
                authorizedUrls: new[] { "<your function app url>" },
                scopes: new[] { "<the function app  API scope your define>" });
        }
    }
    
    
    1. Program.cs中添加如下代码。
     public static async Task Main(string[] args)
            {
                var builder = WebAssemblyHostBuilder.CreateDefault(args);
                builder.RootComponents.Add<App>("app");
                 // register CustomAuthorizationMessageHandler 
                builder.Services.AddScoped<CustomAuthorizationMessageHandler>();
                // configure httpclient
                // call the following code please add packageMicrosoft.Extensions.Http 3.1.0
                builder.Services.AddHttpClient("ServerAPI", client =>
                  client.BaseAddress = new Uri("<your function app url>"))
                        .AddHttpMessageHandler<CustomAuthorizationMessageHandler>();
                // register the httpclient
                builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
                 .CreateClient("ServerAPI"));
                // configure Azure AD auth
                builder.Services.AddMsalAuthentication(options =>
                {
                    builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
                    options.ProviderOptions.DefaultAccessTokenScopes.Add("<the function app  API scope your define>");
    
    
                });
    
                await builder.Build().RunAsync();
            }
    
    
    1. 调用 API
    @page "/fetchdata"
    @using Microsoft.AspNetCore.Components.WebAssembly.Authentication
    @inject HttpClient Http
    
    <h1>Call Azure Function</h1>
    
    <p>This component demonstrates fetching data from the server.</p>
    
    <p>Result: @forecasts</p>
    
    <button class="btn btn-primary" @onclick="CallFun">Call Function</button>
    
    @code {
        private string forecasts;
    
        protected async Task CallFun()
        {
            forecasts = await Http.GetStringAsync("api/http");
        }
    
    
    }
    
    

    【讨论】:

    • 感谢您的回答,但我已经可以像您的示例一样直接调用该函数。使用“Azure API 管理”作为网关时会出现问题。
    • @GuilhermeMolin,在调用 API 时,您是否收到该错误?
    • 调用Azure函数直接工作“xxx.azurewebsites.net/Teste”使用“azure api管理”作为网关不调用前者的“example-api.azure-api.net/teste/Teste” .
    猜你喜欢
    • 1970-01-01
    • 2014-11-25
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    • 2020-10-12
    • 2021-10-20
    相关资源
    最近更新 更多