Search code examples
c#asp.net-mvcauthorizationaction-filterauthorize-attribute

I can't decorate whole Controller with my Custom Authorize Attribute


I try to decorate a full controller class like this:

namespace SisParkTD.Controllers
{
    [CustomAuthorize]
    public class AbonosController : Controller
    {

I can decorate the methods in the controller but can't decorate the full controller.

The error i get when i try to decorate the controller class is this:

The attribute 'CustomAuthorize' is not valid on this declaration type. It is only valid on 'method' declarations.

Attribute 'SisparkTD.Filters.CustomAuthorizeAttribute' is not valid on this declaration type. Is is valid on 'Method' declarations only.

Here is the code for the CustomAuthorizeAttribute:

namespace SisParkTD.Filters
{
    [AttributeUsage(AttributeTargets.Method)]
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            using (var db = new SpContext())
            {
                var controller = (string)httpContext.Request.RequestContext.RouteData.Values["controller"];
                var action = (string)httpContext.Request.RequestContext.RouteData.Values["action"];
                var accion = db.Acciones.FirstOrDefault(a => a.Descripcion == action && a.Pagina.Descripcion == controller);
                var username = httpContext.User.Identity.Name;
                var usuario = db.Usuarios.FirstOrDefault(u => u.NombreDeUsuario == username);

                if (usuario == null) return false;
                if (accion == null) return false;
                var rolesId = db.RolesUsuarios.Where(ru => ru.UsuarioId == usuario.UsuarioId).Select(ru => ru.RolId);
                if (!rolesId.Any()) return false;

                foreach (var rolId in rolesId)
                {
                    if (db.Permisos.Find(rolId, accion.AccionId) != null) return base.AuthorizeCore(httpContext);
                }
                return false;
            }
        }
    }
}

Solution

  • Remove [AttributeUsage(AttributeTargets.Method)] from the attribute. (credit to SLaks for the answer)