pomarc pomarc - 1 month ago 9
ASP.NET (C#) Question

subdomain CORS in webApi 2

I am using WebApi like I've learnt from http://t.co/mt9wIL8gLA

It all works well if I know exactly the perfect origin URI of my client's requests.
Too bad I am writing an enterprise-wide API, so my request to, say
http://apps.contoso.com/myApp/api/foobar

may come from apps all over my domain, say:

http://apps.contoso.com/CRMApp

http://apps.contoso.com/XYZ

http://www.contoso.com/LegacyApp

http://test.contoso.com/newApps/WowApp
...
and all the new apps my enterprise builds.

What is the best way to approach this? using

Origins="*"
is cheesy, adding origins to my WS source and redeploy is cheesier.

My current solution is writing a custom CorsPolicyAttribute like in http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#cors-policy-providers

and read the allowed origins from appsettings in web.config.
A LITTLE better could be, inside the custom attribute, checking if the request Origin: header is from contoso.com, maybe with a regexp, and add it to allowed origins.

I am wondering if there is a better, more standard, way.

Answer

Use a DynamicPolicyProviderFactory. That's what I use...I even posted a question about it the other day that kind of shows how to add the allowed domains to the web.config file.

Comments