Sitecore10 MVC AuthorizationFilterAttribute OnAuthorization method is not firing

37 views Asked by At

Authorization filter attribute is not firing

 public class AuthenticationRequiredAttribute : System.Web.Http.Filters.AuthorizationFilterAttribute
    {
        public override bool AllowMultiple
        {
            get { return false; }
        }
        
        public override void OnAuthorization(HttpActionContext actionContext)
        {            
            base.OnAuthorization(actionContext);
           
        }

I have decorated controller with the attribute

 [AuthenticationRequired]
    public class ProfileController : BaseController
    {        
        public ProfileController(IMyRepository repository)
            : base(repository)
        {
        }
    }

The AuthenticationRequired filter is not firing, what am I missing?

1

There are 1 answers

0
Kate Orlova On

You seem to be using a Web API filter instead of an MVC filter. Inherit your custom authorization filter from System.Web.Mvc.FilterAttribute class and System.Web.Mvc.IAuthorizationFilter interface, and implement OnAuthorization() method.

For example,

using System.Web.Mvc;
using Sitecore;


namespace {YOUR_PROJECT_NAMESPACE}
{
    public class AuthenticationRequired : System.Web.Mvc.FilterAttribute, System.Web.Mvc.IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            {YOUR_CUSTOM_CODE_LOGIC}
        }
    }

}

You can configure your custom filter in your application at three levels:

  • Global level by registering your filter in Application_Start event of Global.asax.cs;

  • Controller level by decorating a controller with your filter by putting your filter at the top of the controller name;

  • Action level by decorating a given action method with your filter in a similar way as above for controllers.

In your case you simply need to decorate your controller with your custom filter.

Hope this helps.