Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Authorize Filter Order Execution with ValidateAntiForgeryToken

I am using couple of Authorize Filter on a method.

[SessionState(SessionStateBehavior.Required)]
public class AuthenticationFilterAttribute : AuthorizeAttribute {}

[HttpPost]
[AuthenticationFilter]
[ValidateAntiForgeryToken]
public void SaveProgress(string data) {}

Both of them are authorize filter, so I expected AuthenicationFilter to run before the ValidateAntiForgeryToken filter. But the ValidateAntiForgeryToken runs before the Authentication filter.

I know that this can be solved by the Order property. But I want to know the reason of this behaviour, and I want to make sure it executes in that order (within the corresponding filter types - authorize, action..so on).

like image 630
DarkKnight Avatar asked Oct 22 '13 22:10

DarkKnight


1 Answers

Filter execution order is defined by their types, their Order and finally their Scopes.

From msdn :

Filter Order

Filters run in the following order:

  1. Authorization filters
  2. Action filters
  3. Response filters
  4. Exception filters

For example, authorization filters run first and exception filters run last. Within each filter type, the Order value specifies the run order. Within each filter type and order, the Scope enumeration value specifies the order for filters. This enumeration defines the following filter scope values (in the order in which they run):

  1. First
  2. Global
  3. Controller
  4. Action Last

For example, an OnActionExecuting(ActionExecutingContext) filter that has the Order property set to zero and filter scope set to First runs before an action filter that has the Order property set to zero and filter scope set to Action. Because exception filters run in reverse order, an exception filter that has the Order property set to zero and filter scope set to First runs after an action filter that has the Order property set to zero and filter scope set to Action.

And finally :

The execution order of filters that have the same type, order, and scope is undefined.

Your ValidateAntiForgeryToken and Authorize filters are of same type, order and scope too (both being undefined) so the execution order will be undefined. From then, your only option is, as you already know, to define an Order property for both.

For your information, FilterScope property does not show up in my Intellisense but after typing it, it finally appears.

like image 70
AirL Avatar answered Sep 20 '22 08:09

AirL