.NET 5 WEB API - Can't configure CORS with subdomain (or even with the full domain name)

Amir Dar 1 Reputation point
2022-11-28T11:19:44.857+00:00

I'm having a problem with configuring CORS in our web API project.

in Startup.cs we have the following configuration:

protected override void ConfigureApplication(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime)  
{  
     base.ConfigureApplication(app, env, appLifetime);  
     app.UseCors();  
  
     // ....   
}  
  
public override void ConfigureServices(IServiceCollection services)  
{  
   // ...  
   this.ConfigureCrossOrigin(services);  
   // ...  
}  
         
  
private void ConfigureCrossOrigin(IServiceCollection services)  
{  
    string[] allowedOrigin = new string[]  
    {  
        "https://dev-XX.myapp.nl/",  
        "https://*.myapp.nl/"  
    };  
  
    services.AddCors(options =>  
        options.AddDefaultPolicy(builder =>  
            builder  
                .SetIsOriginAllowedToAllowWildcardSubdomains()  
                .WithOrigins(allowedOrigin)  
                .AllowCredentials()  
                .AllowAnyMethod()  
                .AllowAnyHeader()));  
}  

Now, we have a client website that URL is https://dev-XX.myapp.nl/

and our server (API) is running at https://dev-api.myapp.nl/

so, for example, when the client site wants to perform a login it will send a POST request to https://dev-api.myapp.nl/api/login

The problem is that no matter what variation I put in the allowedOrigins I get a CORS error I tried:

"https://*.myapp.nl/" , "https://*-XX.myapp.nl/", "https://dev-XX.myapp.nl/"  

nothing seems to work!

By the way, we have a "development" mode that allows all origins to send requests to the API and we configure it as follows:

private void ConfigureCrossOrigin(IServiceCollection services)  
{  
    string[] allowedOrigin = new string[]  
    {  
        "https://dev-XX.myapp.nl/",   
        "https://*.myapp.nl/"  
    };  
  
    services.AddCors(options =>  
        options.AddDefaultPolicy(builder =>  
            builder  
                .SetIsOriginAllowed(_ => true)  
                .AllowAnyMethod()  
                .AllowAnyHeader()  
                .AllowCredentials()));  
}  

This works just fine but I don't want to allow such a thing in production

So, how do I achieve using CORS with a subdomain?

edit: I forgot to mention that since we are using http-only cookies we must configure the AllowCredentials function

thanks!

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,491 Reputation points
    2022-11-28T16:14:26.123+00:00

    CORS only allow exact domain/path list or wildcard * (any)

    https://*.myapp.nl is not valid.

    You must list all the subdomains.