Search code examples
c#asp.net-coreasp.net-core-mvccors

Configure cors to allow all subdomains using ASP.NET Core (ASP.NET 5, MVC6, VNext)


I have CORS setup correctly in an ASP.NET Core web app. I'm using the following package...

"Microsoft.AspNet.Cors": "6.0.0-rc1-final"

and here is the startup.cs snippet...

public virtual IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddCors
    (
        options =>
        {
            options.AddPolicy
            (
                CORSDefaults.PolicyName, 
                builder =>
                {
                    //From config...
                    var allowedDomains = new []{"http://aaa.somewhere.com","https://aaa.somewhere.com","http://bbb.somewhere.com","https://bbb.somewhere.com"};
                    
                    //Load it
                    builder
                        .WithOrigins(allowedDomains)
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                }
            );
        }
    );
}

This works great except that the list of subdomains to allow is growing fast and I want to allow all subdomains of "somewhere.com". Something like "*.somewhere.com". I cant seem to find any documentation on how to do this in the new ASP.NET Core (MVC6, ASP.NET5, VNext). All the docs/examples I'm finding that demonstrate how to do this are for earlier versions of MVC or WebApi. How can I achieve this in the new stack?


Solution

  • This has now been implemented in version 2.0.0. In your ConfigureServices use the following:

    options.AddPolicy("MyCorsPolicy",
       builder => builder
          .SetIsOriginAllowedToAllowWildcardSubdomains()
          .WithOrigins("https://*.mydomain.com")
          .AllowAnyMethod()
          .AllowCredentials()
          .AllowAnyHeader()
          .Build()
       );
    

    Also, don't forget to call UseCors in your Configure call too:

    app.UseCors("MyCorsPolicy");