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

2

6

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.

Ohaus answered 17/3, 2010 at 3:28 Comment(0)
B
7

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.

Barbwire answered 5/6, 2011 at 13:15 Comment(1)
Thanks. I later found this out and ended up doing what you recommended anyway.Ohaus
I
1

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.

Incrocci answered 17/3, 2010 at 3:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.