public class AdministratorAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
EFUserRepository repo = new EFUserRepository();
var user = repo.FindUserByUserName(filterContext.HttpContext.User.Identity.Name);
if (user.UserRole.Name == "Administrator")
{
filterContext.Result = new RedirectToRouteResult(//Redirect to the original action they tried to enter?
}
}
else
{
//redirect to the "Home/Index" area.
}
}
}
I’m having trouble redirecting to an action from within this OnActionExecuting method. Also, how would I redirect the user to their original intended action if they are fully authorized.
This [Administrator] attribute is going to be placed on many different controllers, so I have to have a way to redirect to the appropriate ActionResult they were trying to reach.
The usual way to do this is, for a GET at least, to url-encode the requested url and include it. For example, for SO if we start on this question as anonymous, and click login, we are taken to
The same would work for a redirect; once you have completed login, check for a
returnurlparameter, and back you go.You should, however, check that the target url is either relative (same-site), or absolute to the current site or another site you own/etc (see OWASP for details – in particular “Example Scenarios”).