IdentityServer4 CORS 问题

IdentityServer4 CORS issue

我们已经为使用 IdentityServer4 作为身份验证提供程序的 .NET 5 Web API 设置了 CORS。

从我们的 JS 客户端 (Ionic/Capacitor) 到 /account/register 的 HTTP 调用没有问题,但是当我们调用我们的“自定义”之一时 API方法我们得到以下错误信息。

2021-02-19 10:38:10.092 +00:00 [DBG] CORS request made for path: /connect/userinfo from origin: http://192.168.1.152:8100
2021-02-19 10:38:10.099 +00:00 [DBG] Client list checked and origin: http://192.168.1.152:8100 is allowed
2021-02-19 10:38:10.101 +00:00 [DBG] CorsPolicyService allowed origin: http://192.168.1.152:8100
2021-02-19 10:38:10.179 +00:00 [DBG] CORS request made for path: /api/schedule from origin: http://192.168.1.152:8100 but was ignored because path was not for an allowed IdentityServer CORS endpoint

我们用谷歌搜索了这个问题,但我们似乎唯一找到的是如何为 IDS4 或 .NET 5 配置 CORS。我们的 CORS 是这样设置的。

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddDefaultPolicy(builder =>
            {
                builder.WithOrigins("http://192.168.1.152:8100", "capacitor://localhost", "https://localhost:5001")
                .AllowAnyHeader()
                .AllowAnyMethod();
            });
    });

    // ...

    services.AddIdentityServer();

    // ...
}

之后,我们还尝试像这样在适当的客户端上设置 AllowedCorsOrigins 属性。但是运气不好。

AllowedCorsOrigins = new List<string>
{
    "http://192.168.1.152:8100", 
    "capacitor://localhost"
}

配置设置是这样完成的,我们尝试切换 UseCors() 和 UseIdentityServer() 但这没有帮助。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IMapper mapper)
{
    mapper.ConfigurationProvider.AssertConfigurationIsValid();

    app.UseRouting();
    app.UseStaticFiles();

    app.UseCors();
    app.UseIdentityServer();
    
    app.UseAuthentication();
    app.UseAuthorization();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");

        app.UseHsts();
    }

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapDefaultControllerRoute();
        endpoints.MapControllers();
    });
}

我们还尝试了 IDS4 文档中的“添加更多 API 端点”条目,但这似乎只是为了授权对那些我们已经自行设置的端点的请求。

有人知道发生了什么事吗?

尝试使用命名策略而不是默认策略。有时效果更好:

  services.AddCors(o => o.AddPolicy("AllowSpecificOrigins", builder =>
            {
              builder.WithOrigins("http://192.168.1.152:8100", "capacitor://localhost", "https://localhost:5001")
                .AllowAnyHeader()
                .AllowAnyMethod();
        });
});

......
......

app.UseCors("AllowSpecificOrigins");