【问题标题】:CORS problem with custom controller and CustomClientStore in IdentityServer4IdentityServer4中自定义控制器和CustomClientStore的CORS问题
【发布时间】:2020-12-16 05:00:18
【问题描述】:

我想在 IdentityServer4 中添加一个自定义端点,但是当我从另一个站点调用 API 时,出现了 CORS 错误。 我使用 CustomClientStore 来加载我的客户端,所以我需要添加 CustomCorsPolicyService

Access to XMLHttpRequest at 'http://localhost:8082/embedded/log' from origin 'http://localhost:8080' 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.

在启动中,我添加了我的 CustomClientStore 和 CustomCorsPolicyService

public void ConfigureServices(IServiceCollection services)
{
    ...
    CustomClientStore.Init(_Configuration);

    var builder = services.AddIdentityServer()
        .AddInMemoryIdentityResources(Config.GetIdentityResources())
        .AddInMemoryApiScopes(Config.GetApiScopes())
        .AddRedirectUriValidator<MyUriValidator>();

    builder.Services.AddSingleton<IUserRepository, UserRepository>();
    builder.AddProfileService<CustomProfileService>();

    builder.AddClientStore<CustomClientStore>();
    //services.AddCors(setup => setup.AddDefaultPolicy(b => b.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));

    builder.AddCorsPolicyService<CustomCorsPolicyService>();
    ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();
    
    app.UseStaticFiles();
    
    // Add this before any other middleware that might write cookies
    app.UseCookiePolicy();
    
    app.UseIdentityServer();
    
    app.UseRouting();
    app.UseCors();
    app.UseMvcWithDefaultRoute();
    
    // This will write cookies, so make sure it's after the cookie policy
    app.UseAuthentication();
}

在我的控制器中


[ApiController]
public sealed class EmbeddedLogController : ControllerBase
{
    [HttpPost]
    [Route("/embedded/log/")]
    [EnableCors()]
    public ActionResult Log(ParametersLog parameters)
    {
        ....
    }
}

如果没有 CustomClientStore,我可以调用 services.AddCors(setup =&gt; setup.AddDefaultPolicy... 来接受 CORS 但是现在我需要使用 builder.AddClientStore&lt;CustomClientStore&gt;(); 因为 CustomProfileService。

我该如何解决? 谢谢

【问题讨论】:

    标签: asp.net-core cors identityserver4


    【解决方案1】:

    这个 GitHub issue 可能会给你一些线索。

    也就是说:

    已解决当使用 Endpoint Routing CORS 和 IdentityServer4 时,调用 到 UseCors() 必须在 UseRouting() 之后但在 UseIdentityServer() 之前 和使用授权()。否则它似乎可以工作,但是 飞行前检查将失败

    【讨论】:

      猜你喜欢
      • 2021-05-22
      • 2013-06-23
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-28
      • 1970-01-01
      相关资源
      最近更新 更多