Search code examples
asp.netasp.net-web-apiodataasp.net-web-api2odata-v4

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.


Solution

  • 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());