AllowAnonymous does not work MVC5

I use a custom filter (defined as follows):

if (user == null || !user.Active) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { {"controller", "Home"}, {"action", "NotAuthorized"} }); } base.OnActionExecuting(filterContext); 

This is done on the site (in RegisterGlobalFilters() in FilterConfig.cs. However, there is one page that I would like to allow access to on the NotAuthorized page. In HomeController, I created the following ActionResult method:

  [AllowAnonymous] public ActionResult NotAuthorized() { return View(); } 

Unauthorized behavior leads the user to this view, but it leads to a redirect cycle (probably because the filter is still running on this page).

How to allow anonymous users access to this page?

+6
source share
2 answers

You need to check the attribute in your custom filter.

Try:

 if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), false) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), false) && (user == null || !user.Active)) { //.... } 
+12
source

Check AllowAnonymousAttribute in your custom filter. Here is one possible way to do this.

Add the following extension method.

 public static class MyExtensionMethods { public static bool HasAttribute(this ActionExecutingContext context, Type attribute) { var actionDesc = context.ActionDescriptor; var controllerDesc = actionDesc.ControllerDescriptor; bool allowAnon = actionDesc.IsDefined(attribute, true) || controllerDesc.IsDefined(attribute, true); return allowAnon; } } 

Then use it in your filter.

 public class MyActionFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { // use the extension method in your filter if (filterContext.HasAttribute(typeof(AllowAnonymousAttribute))) { // exit early... return; } // ...or do whatever else you need to do if (user == null || !user.Active) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, { "action", "NotAuthorized" } }); } base.OnActionExecuting(filterContext); } } 

Here is a script that implements the solution .

+2
source

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


All Articles