Run authorization filter and action filter for unauthorized ASP.NET MVC request

I decorated my base controller with several action filters. They work great.

One of these filters customizes the request β€” it does things like setting up a culture based on a domain, etc.

I also have several actions that require authorization using the Authorize attribute.

My problem is that when a user tries to request a page that they don’t have access to, the authorization filter launches and redirects them to the page, telling them that they cannot compete with the page.

The problem is that action filters never run, so culture and other query data are never set. This actually leads to misuse of the language in the view and other data that will be missing.

I know that authorization filters are started first, but my question is this: how can I create this in such a way that I can guarantee that certain methods will always be executed until the view returns, regardless of authorization.

Hope this makes sense.

+4
source share
2 answers

In accordance with this documentation (in the heading "Filter Order"), authorization filters always start before action filters. This means that clutter in the Order properties will not help.

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

+5
source

See Procedure for action filters on the MSDN Article on Action Filter

Basically, you can provide the Order property for these culture filters so that it runs before the authorization filter, something like this:

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

...

If this fails, you can execute the code before the action is completed and before any ActionFilter is executed.

+1
source

Source: https://habr.com/ru/post/1304331/


All Articles