goroth goroth - 1 year ago 122
ASP.NET (C#) Question

ASP.NET allow anonymous access to OData $metadata when site has global AuthorizeAttribute

I have an ASP.NET OData site that has the following in the WebApiConfig file:

config.Filters.Add(new AuthorizeAttribute())

This forces all callers to authenticate before calling any of the controllers.

Unfortunately, this also forces user authentication to access the "$metadata" url.

I need to globally force authentication for all controller access while also allowing anonymous access the the "$metadata" url.

Answer Source

Create a custom filter that derives from AuthorizeAttribute and override the IsAuthorized method as follows:

public class CustomAuthorizationFilter : AuthorizeAttribute
    protected override bool IsAuthorized(HttpActionContext actionContext)
        if (actionContext.Request.RequestUri.AbsolutePath == "/$metadata" ||
            actionContext.Request.RequestUri.AbsolutePath == "/%24metadata")
            return true;

        return base.IsAuthorized(actionContext);

Register the filter:

config.Filters.Add(new CustomAuthorizationFilter());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download