In a project I’m working on there are two custom ActionFilterAttribute classes which are injected using ninjects BindFilter:
kernel.BindFilter<LogErrorsAttribute>(FilterScope.Last, 0);
kernel.BindFilter<CriticalErrorAttribute>(FilterScope.Last, 1);
These have been working fine.
I created a custom IAuthorizationFilter filter which is also injected using BindFilter:
kernel.BindFilter<AuthorizationFilter>(FilterScope.Action, null).WhenActionMethodHas<Authorise>().WithPropertyValueFromActionAttribute<Authorise>("Roles", n => n.Roles).WithPropertyValueFromActionAttribute<Authorise>("Years", n => n.Years);
On it’s own, this works fine too.
I just discovered that if I apply the Authorise tag to an action, the two custom ActionFilterAttribute classes are no longer called.
I’m stumped on why this would be occuring. My custom IAuthorizationFilter looks like this:
public class AuthorizationFilter : IAuthorizationFilter
{
private readonly string[] RolesHaveAccessToApplication;
public AuthorizationFilter()
{
//put roles which should allow user to see application, hardcoded for now, but later
//this can be generated from the database
var configRoles = ConfigurationManager.AppSettings["ApplicationRoles"];
if(string.IsNullOrEmpty(configRoles))
throw new Exception("The ApplicationRoles value has not been defined in the web.config file.");
RolesHaveAccessToApplication = configRoles.Split(',');
}
[Inject]
public IUserServices userService { get; set; }
public string Roles { get; set; }
public string Years { get; set; }
protected bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.Request.IsAuthenticated)
return false;
if(!Roles.HasContent() && !Years.HasContent())
{
return RolesHaveAccessToApplication.Any(role => RolesHaveAccessToApplication.Any(n => n == role));
}
var AuthenticatedUserRoles = System.Web.Security.Roles.GetRolesForUser();
bool isAuthorised = false;
//first, lets check against to see if the user has any roles related to the application
isAuthorised = RolesHaveAccessToApplication.Any(role => AuthenticatedUserRoles.Any(n => n == role));
//if they don't, we throw them to access denied page
if (!isAuthorised)
return false;
#region CheckRoles
if (!string.IsNullOrEmpty(Roles) && AuthenticatedUserRoles.HasContent())
{
var authRoles = Roles.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries);
isAuthorised = authRoles.Any(role => AuthenticatedUserRoles.Any(n => n == role));
}
#endregion
#region CheckYears
if (!string.IsNullOrEmpty(Years) && AuthenticatedUserRoles.HasContent())
{
if (AuthenticatedUserRoles.Any(n => n == "Student"))
{
var yearRoles = Years.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var user = userService.FetchUser(httpContext.User.Identity.Name);
if (user != null)
{
isAuthorised = yearRoles.Any(n => n == user.Year);
}
}
}
#endregion
return isAuthorised;
}
public void OnAuthorization(AuthorizationContext filterContext)
{
if(filterContext == null)
throw new Exception("filtercontext is null");
if (!filterContext.HttpContext.Request.IsAuthenticated)
HandleUnauthorizedRequest(filterContext);
if (AuthorizeCore(filterContext.HttpContext))
SetCachePolicy(filterContext);
else
HandleUnauthorizedRequest(filterContext);
}
protected void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
filterContext.Result = new RedirectResult(new UrlHelper(filterContext.RequestContext).Action("Denied", "Home", new {Area = ""}));// new ViewResult { ViewName = "~/Home/Denied", View = new RazorView("Home") //ViewData = viewData };
else
filterContext.Result = new HttpUnauthorizedResult();
}
protected void SetCachePolicy(AuthorizationContext filterContext)
{
..snip..
}
}
//Used as a filter for actions, and ninject is configured to bind AuthorizationFilter to this
public class Authorise : ActionFilterAttribute
{
public string Roles { get; set; }
public string Years { get; set; }
}
Any help with resolving this would be appreciated.
Edit:
This is one of the other filters:
public class CriticalErrorAttribute : ActionFilterAttribute
{
[Inject]
public IErrorServices ErrorService { private get; set; }
public override void OnActionExecuted(ActionExecutedContext filterContext)
{ //if the request is an ajax request, we don't want a redirect to happen
//the controller dealing with the ajax request can fetch the critical
//errors and pass them back to the user for display
if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
var criticalErrors = ErrorService.FetchCriticalErrors();
if (criticalErrors.HasContent())
{
var helper = new UrlHelper(filterContext.RequestContext);
var url = helper.Action("Error", "Home", new { area = "" });
filterContext.Controller.TempData["CriticalErrorList"] = criticalErrors;
filterContext.Result = new RedirectResult(url);
}
}
base.OnActionExecuted(filterContext);
}
}
If a domain object couldnt be hydrated, it would log a critical error. This filter checks for such errors, if they occur it directs the user to an error page.
Solved:
It turns out Darin was correct! But the issue was being hidden by my configuration of my filters.
Firstly, I had [Authorise] on navigation items, and secondly I was binding the CriticalErrorAttribute to every action.
So each time a menu was built (welcome, left, nav, sub) – this filter was firing. At some point during this chain of filter calls, results were being applied to filterContext.Result – the later results hiding the earlier (correct) result.
To overcome this issue, I tweaked the BindFilter configuration line for CriticalErrorAttribute to this:
kernel.BindFilter<CriticalErrorAttribute>(FilterScope.Last, 0).When( (context, ad) =>
context.RouteData.DataTokens["action"] != null && context.RouteData.DataTokens["action"] !=
"Error" && context.RouteData.DataTokens["controller"] != "Navigation");
Everything works perfectly now!
Here:
you are assigning a result. And according to the documentation: