Search code examples
asp.net-mvcauthenticationaction-filter

Execute code in custom Attribute before the MVC AuthorizeAttribute


The Problem
Create a custom IAuthorizeAttribute which will execute before the default MVC AuthorizeAttribute. The default AuthorizeAttribute always seems to run before my custom attribute.

Things I have tried

  • I made a custom attribute which inherits from IAuthorizationFilter.
  • I've registered this attribute as a globalfilter like so:
    filters.Add(new HandleCrossDomainAuthenticationAttribute() { Order = 1 });
  • I already read about action filters on msdn: http://msdn.microsoft.com/en-us/library/dd381609.aspx

The custom attribute

public class HandleCrossDomainAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
{
    #region IAuthorizationFilter Members

    void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            tryCrossDomainAuthentication(filterContext); //this will set the filterContext.Result to a certain url
        }
    }

    #endregion
}

Other observations
When I specify an Order = 2 on the AuthorizeAttribute that is giving me a hard time, It does work. But this is not a very manageable way to go...


Solution

  • I must have read the msdn article the way I wanted it to be...

    The Order property takes an integer value that must be 0 (the default) or greater, with one exception. Omitting the Order property gives the filter an order value of -1, which indicates an unspecified order. Any action filter in a scope whose Order property is set to -1 will be executed in an undetermined order, but before the filters that have a specified order.

    So reading this, it seems to be impossible to do what I want unless you write a custom AuthorizeAttribute or a custom ControllerActionInvoker. That really sucks!