Zichen Ma
Zichen Ma

Reputation: 987

CORS Origin issue using ASP.NET Core 3.1

I am encountering a weird CORS issue when using C# ASP.NET Core 3.1 and GraphQL (Version="3.3.2"). In the Startup.cs file, I have setup the UseCors like this:

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
    if (Environment.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCors (x => x
                .AllowAnyOrigin ()
                .AllowAnyMethod ()
                .AllowAnyHeader ());
            ...
}

And also create a ConfigureCors function like this:

private void ConfigureCors(IServiceCollection services)
{
    var requestOrigins = Configuration.GetSection("RequestOrigins")?
                .GetChildren()
                .Select(url => url.Value)
                .ToArray() ?? new string[] {};
            
    services.AddCors(options =>
            {
                options.AddPolicy(name: AllowSpecificOrigins,
                    builder =>
                    {
                        builder.WithOrigins(requestOrigins)
                            .AllowAnyHeader()
                            .AllowCredentials()
                            .AllowAnyMethod();
                    });
            });
}

Called the ConfigureCors like this:

public void ConfigureServices(IServiceCollection services)
{
         ConfigureCors(services);
         ...
}

In appsetting.{env}.json, I set the RequestOrigins:

"RequestOrigins": [
    "http://localhost:8889"
  ]

When using frontend React to call the mutation like this:

const link = new HttpLink({
  uri: 'https://localhost:5001/graphql/v1',
  fetchOptions: {
    credentials: 'include'
  },
  headers : {Authorization: `Bearer ${localStorage.getItem('Token')}`}
})

export default new ApolloClient({
  link,
  cache
});

It will throw the CORS issue:

Access to fetch at 'https://localhost:5001/graphql/v1' from origin 'http://localhost:8889' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

However the backend log shows:

info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 OPTIONS https://localhost:5001/graphql/v1

info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
CORS policy execution successful.

I am very confused:

  1. Why are the OPTIONS not the POST, since I am calling a graphql mutation?
  2. Why backend shows CORS policy execution successful, but frontend got CORS blocker?

However, if I commented out the Authentication part like this:

const link = new HttpLink({
      uri: 'https://localhost:5001/graphql/v1',
      //fetchOptions: {
        //credentials: 'include'
      //},
      //headers : {Authorization: `Bearer ${localStorage.getItem('Token')}`}
    })

Got the authorization failed error, but not CORS blocker. The token I have validated work in Postman. If I remove the app.UseCors, the CORS blocker comes back which is understandable. My guess is some CORS related configuration I didn't do right, but not sure which part, anyone knows what's going on? Thanks a lot!

Upvotes: 0

Views: 694

Answers (1)

Pouya Hashemi
Pouya Hashemi

Reputation: 266

based on Microsoft Doc's in this link when ever u add new policy u need to specify that policy to app.UseCors(). and also pay attention to this

The call to UseCors must be placed after UseRouting, but before UseAuthorization. For more information, see Middleware order.

Upvotes: 2

Related Questions