How would you configure CORS to allow any subdomain of a known domain (like *.mycompany.com) using SetIsOriginAllowed with custom matching logic?
Short answer
Since WithOrigins() requires exact origin string matches, allowing a dynamic pattern like any subdomain requires SetIsOriginAllowed(Func ) with custom logic checking the origin's host suffix, carefully validated to avoid accidentally matching an attacker-controlled domain that…
Advertisement
AModel answer
Since WithOrigins() requires exact origin string matches, allowing a dynamic pattern like any subdomain requires SetIsOriginAllowed(Func<string, bool>) with custom logic checking the origin's host suffix, carefully validated to avoid accidentally matching an attacker-controlled domain that merely contains the expected substring (like evilmycompany.com) rather than genuinely being a subdomain.
policy.SetIsOriginAllowed(origin => {
var uri = new Uri(origin);
return uri.Host.Equals("mycompany.com", StringComparison.OrdinalIgnoreCase) ||
uri.Host.EndsWith(".mycompany.com", StringComparison.OrdinalIgnoreCase);
}).AllowCredentials();Real-world example
A multi-tenant SaaS platform where each customer gets a subdomain (customer1.mycompany.com) uses carefully-validated SetIsOriginAllowed matching logic to permit any valid tenant subdomain without needing to update the CORS policy every time a new customer signs up.
Likely follow-ups
- What's the risk of a naive string.Contains() check instead of proper suffix matching here?
- How would you unit test this custom origin-matching logic thoroughly?
Related topics