Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run both Authorize Filter and Action Filter on unauthenticated ASP.NET MVC request

I have decorated my base controller with a couple of action filters. They work fine.

One of those filters sets up the request - does things like set the culture based on the domain, etc.

I also have a handful of actions that require authorization using the Authorize attribute.

My problem is that when an user attempts to request a page they are not authorized to access, the authorization filter kicks in and redirects them to a page telling them that they cannot vie the page.

The issue is that the action filters never run so the culture and other request data is never set. This effectively causes language to be wrong in the view and other data to be missing.

I know that authorization filters run first but my question is this: How can I design this such that I can ensure that certain methods are always run before the view is returned, regardless of the authorization.

Hope that makes sense.

like image 937
Bryan Migliorisi Avatar asked Mar 17 '10 03:03

Bryan Migliorisi


2 Answers

According to this documentation (under the Filter Order header), Authorization filters always run before Action filters. This means that messing with Order properties won't help.

I think the best way to handle this is to write your own Authorization attribute (by subclassing AuthorizeAttribute and overriding AuthorizeCore) and running your action filters manually when authorization fails.

like image 84
hwiechers Avatar answered Nov 18 '22 18:11

hwiechers


See Order of Execution for Action Filters on MSDN Article on Action Filter

Basically, you can supply an Order property on those culture filters so it runs before the Authorization filter, something like this:

[CultureRedirect(Order = 1)]
public class MyBaseController : Controller { }

[Authorize(Order = 2)]
public class RequiresAuth : MyBaseController { }

...

If that fails, you can still Execute code bfore an action executes and before any ActionFilter will executes.

like image 31
chakrit Avatar answered Nov 18 '22 20:11

chakrit