AuthorizedAttribute with custom redirect

I want to use the standard AuthorizeAttribute attribute (i.e. do not inherit it), but with a custom redirect. Is it possible? where should i check 401 and redirect?

I tried to add

<customErrors mode="On" > <error statusCode="401" redirect="/Errors/NotAuthorized/" /> </customErrors> 

but it didn’t work.

+4
source share
1 answer

This was in my ApplicationController application:

  protected override void OnAuthorization(AuthorizationContext filterContext) { var attributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true); if (attributes.Length == 0) attributes = GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true); if (attributes.Length == 0) return; foreach (AuthorizeAttribute item in attributes) { if (!Thread.CurrentPrincipal.IsInRole(item.Roles)) { filterContext.Result = new RedirectResult("/Errors/Unauthorized"); } } } 

I will reward everyone who has the best solution.

+7
source

All Articles