Advertisement
Intermediate .NET, CORS & Cross-Origin Resource Sharing

How would you set up a CORS policy that allows any subdomain of a given domain (like *.mycompany.com) using SetIsOriginAllowed?

Short answer

Since WithOrigins() requires exact origin string matches, allowing a dynamic pattern like any subdomain requires SetIsOriginAllowed(Func ), which lets you write custom matching logic (e.g., checking if the origin's host ends with '.mycompany.com') evaluated per-request, rather…

Save .NET mock interview
Advertisement
AModel answer
Since WithOrigins() requires exact origin string matches, allowing a dynamic pattern like any subdomain requires SetIsOriginAllowed(Func<string, bool>), which lets you write custom matching logic (e.g., checking if the origin's host ends with '.mycompany.com') evaluated per-request, rather than needing to enumerate every possible subdomain explicitly in advance.
options.AddPolicy("AnySubdomain", policy => {
    policy.SetIsOriginAllowed(origin => {
        var uri = new Uri(origin);
        return uri.Host.EndsWith(".mycompany.com", StringComparison.OrdinalIgnoreCase);
    }).AllowCredentials().AllowAnyHeader().AllowAnyMethod();
});
Real-world example
A multi-tenant SaaS platform where each customer gets a subdomain (customer1.mycompany.com, customer2.mycompany.com) uses SetIsOriginAllowed to permit any valid tenant subdomain without needing to update the CORS policy every time a new customer signs up.
Likely follow-ups
  • What security risks arise from an overly loose subdomain-matching pattern?
  • How would you validate the pattern doesn't accidentally match an attacker-controlled domain like evilmycompany.com?
Related topics