1
votes

I have a global CORS policy which is applicable for all the endpoints but I want to override this policy for the signalR hub end point.

Here is my ConfigureServices method which has a global CORS policy which I cant modify

    public void ConfigureServices(IServiceCollection services)
    {    
       // some piece of code before adding CORS

        services.AddCors(o =>
        {
            o.AddDefaultPolicy(p =>
            {
                p.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
            });
        });

        // some piece of code after adding CORS
    }

Here is the Configure method

    public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
    {
        app.UseCors();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endPoints =>
        {
            endPoints.MapControllers();
            endPoints.MapHub<NotificationHub>("/notificationHub")
            .RequireCors((builder) =>
            {
                builder
                .WithOrigins(_configuration.GetValue<string>("Settings:ClientAppUrl"))
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();
            });
        });
    }

As it is clear that I have overwritten the CORS policy for the particular endpoint of signal which is /notificationHub.

I am getting the same CORS error in the browser as I was getting before adding the CORS policy for the /notificationHub/negotiate

Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow->Credentials' header in the response is '' which must be 'true' when the request's credentials mode is >'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the >withCredentials attribute.

Also please note that if I add AllowCredentials() method in the global CORS policy then signalR works properly but my objective here is to add the new CORS policy only for the signalR endpoint.

I am not using OWIN CORS, it is just Microsoft.AspNetCore.Cors.

1

1 Answers

1
votes

I have found the fix for this. It is simple but often ignored.

The order of middleware matters here a lot. By swapping the below two middleware, I got it working.

OLD

app.UseCors();
app.UseRouting();

NEW

app.UseRouting();
app.UseCors();

If anyone facing this issue, try doing this. It would definitely work.

This doc from Microsoft supports this claim.