Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

I ended up just writing an AuthorizationFilterAttribute, although I might have just done a regular FilterAttribute.

public class FilterReferals : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var request = actionContext.Request;

        if (!AllowedReferers.GetAllowedReferersList().Contains(request.Headers.Referrer?.Host.ToLower()))
        {
            Challenge(actionContext);
            return;
        }

        base.OnAuthorization(actionContext);
    }

    void Challenge(HttpActionContext actionContext)
    {
        var host = actionContext.Request.RequestUri.DnsSafeHost;
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
        actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", host));
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top