CORS problem with custom controller and CustomClientStore in IdentityServer4

73 views Asked by At

I want to add a custom end-point into IdentityServer4 but when I call API from another site, I have a CORS error. I use a CustomClientStore to load my clients so i need to add 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.

In Startup, I add my CustomClientStore and 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();
}

In My Controller


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

Without CustomClientStore I could call services.AddCors(setup => setup.AddDefaultPolicy... to accept CORS But now I need to use builder.AddClientStore<CustomClientStore>(); because of CustomProfileService.

How can I fix that ? Thanks

1

There are 1 answers

0
Tore Nestenius On BEST ANSWER

this GitHub issue might give you some clues.

That says:

Solved When using Endpoint Routing CORS and IdentityServer4, the call to UseCors() must be after UseRouting() but BEFORE UseIdentityServer() and UseAuthorization(). Otherwise it will appear to work but Pre-Flight checks will fail