【问题标题】:Request ignored because of CORS in IdentityServer4由于 IdentityServer4 中的 CORS,请求被忽略
【发布时间】:2021-01-05 16:27:33
【问题描述】:

我有 3 个项目:

  1. 客户端应用
  2. ASP.NET API 应用程序
  3. IdentityServer4 MVC 应用程序

我能够从 API 向 IDP 发送请求,但尝试从客户端向 IDP 发送请求会产生

"CORS request made for path: /api/Trial/TrialAction from origin: https://localhost:44389 but
was ignored because path was not for an allowed IdentityServer CORS endpoint"

即使我在 IDP 中添加了以下内容:

services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", policyBuilder => policyBuilder
        .AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader());
});

// ...
app.UseRouting();
app.UseIdentityServer();
app.UseCors("CorsPolicy");
app.UseAuthorization();
// ...

有趣的是,我可以从 API 向 IDP 发送请求,而无需向 IDP 添加 CORS 配置。我做错了什么?

Config.cs:

public static class Config
{
    public static IEnumerable<IdentityResource> Ids =>
        new IdentityResource[]
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
            new IdentityResources.Email(),
        };

    public static IEnumerable<ApiResource> Apis =>
        new ApiResource[]
        {
            new ApiResource("myapi", 
                "My API", 
                new [] { "membershipType" }
            )
        };

    public static IEnumerable<Client> Clients =>
        new Client[]
        { 
            new Client
            {
                ClientId = "mywebclient",
                ClientName = "My Web Client",
                AllowedGrantTypes = GrantTypes.Code, // Authorization code flow with PKCE protection
                RequireClientSecret = false, // Without client secret
                RequirePkce = true,
                RedirectUris = { "https://localhost:44389/authentication/login-callback" },
                PostLogoutRedirectUris = { "https://localhost:44389/authentication/logout-callback" },
                AllowedScopes = {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    "albidersapi"
                },
                AllowedCorsOrigins = { "https://localhost:44389" },
                RequireConsent = false,
            }           
        };
}

【问题讨论】:

    标签: asp.net identityserver4


    【解决方案1】:

    您是否将客户端和 API 与 IdentityServer 放在同一个项目中?我通常建议您将它们分开。

    一个大胆的猜测可能是交换这两行:

    app.UseIdentityServer();
    app.UseCors("CorsPolicy");
    

    因为显然 IdentityServer 捕获了对 API 的请求?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-14
      • 2021-06-08
      • 2023-01-19
      • 1970-01-01
      • 2019-11-30
      • 2019-10-01
      • 2019-08-07
      • 2013-12-29
      相关资源
      最近更新 更多