Here is my filter attribute:
public class RoleAttribute : ActionFilterAttribute
{
public string Roles { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
EfUsuarioRepository usuarioRepository = new EfUsuarioRepository();
var loggedInUser = usuarioRepository.BuscarCuentaPorCorreo(filterContext.HttpContext.User.Identity.Name);
string[] userRoles = usuarioRepository.GetRolesForUser(loggedInUser.UsuarioId);
foreach (string definedRole in this.Roles.Split(','))
{
foreach (string role in userRoles)
{
if (definedRole.Equals(role))
return;
}
}
throw new SecurityException("Access not granted!");
}
else
{
throw new SecurityException("Access not granted!");
}
}
}
Now my question is what is the preferred way to redirect to an unauthorized page? Do I inject myself into the HttpContext and perform a redirect? What is a proven pattern for this? I just want an “Unauthorized” page as a catch all.
Instead of inheriting from
ActionFilterAttributeyou should inherit fromAuthorizeAttribute.This question has code that looks similar to what you’re trying to do and the return type is a boolean of
trueorfalse.