Home > Enterprise >  Intermittent CORS errors with React and dotnet core 3.1
Intermittent CORS errors with React and dotnet core 3.1

Time:06-03

We are getting INTERMETNT CORS errors with Google Chrome since their update last week. Hey On the CORS, we are getting INTERMETNT CORS errors with Google Chrome since their update last week.

Our ops guy pushed a policy that ignores Access-Control-Allow-Private-Network that seems to help, but that does not help for non-managed computers.

Here is our policy:

services.AddCors(options =>
{
    options.AddPolicy(PolicyName,
        corsBuilder => corsBuilder.AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod());
});


app.UseCors(PolicyName);

CodePudding user response:

We were able to solve this with the following:

Creating a middleware for Private Networking CORS. From Github Issue

    public static class PrivateCorsMiddleware 
    {
        public static Func<HttpContext, Func<Task>, Task> CorsAllowPrivateNetwork()
        {
            return async (ctx, next) =>
            {
                if (ctx.Request.Method.Equals("options", StringComparison.InvariantCultureIgnoreCase) 
                    && ctx.Request.Headers.ContainsKey("Access-Control-Request-Private-Network"))
                {
                    ctx.Response.Headers.Add("Access-Control-Allow-Private-Network", "true");
                }

                await next();
            };
        }

    }
}

Using the Middleware

app.Use(PrivateCorsMiddleware.CorsAllowPrivateNetwork());

Then modifying the policy to use a specific origin to enhance safety.

    services.AddCors(options =>
    {
        options.AddPolicy(PolicyName,
            corsBuilder => corsBuilder
                .WithOrigins(_configuration["CorsAllowedHosts"])
                .AllowAnyHeader()
                .AllowAnyMethod());
    });
  • Related