AuthorizeAttribute in Controlller and Actions

3

When using an attribute (AuthorizeAttribute) developed by me (with Enums), it is not working as it should:

When used to decorate the Controller declaration:

[UserTypeAuthorize(TipoUsuario.Administrador)]
public class UsuarioController : BaseController
{ ... }

It works normally as it should, however when using Actions within this same controller, for all I know, it should overwrite the controller only in this Action in which it is decorated with your other Enums or with the use of [AllowAnonymous] .

The idea is that the attributes in the Actions should override the one defined in the Controller declaration, just as the [AllowAnonymous] does perfectly.

[UserTypeAuthorize(TipoUsuario.Administrador)]
public class UsuarioController : BaseController
{ 
    //não funciona
    [UserTypeAuthorize(TipoUsuario.Administrador, TipoUsuario.Moderador)]
    public ActionResult Edit(Guid id)
    { ... }

    //deveria funcionar somente para Moderador
    [UserTypeAuthorize(TipoUsuario.Moderador)]
    public ActionResult Edit(Guid id)
    { ... }

    //funciona
    [AllowAnonymous]
    public ActionResult Edit(Guid id)
    { ... }
}

My AuthorizeAttribute:

    public class UserTypeAuthorizeAttribute : AuthorizeAttribute
    {
        public UserTypeAuthorizeAttribute(params TipoUsuario[] tiposUsuario)
        {
            Roles = string.Join(",", tiposUsuario.Select(u => u.ToString()));
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectResult(FormsAuthentication.LoginUrl);
        }
    }

NOTE: Authenticated users have their correct types.

    
asked by anonymous 12.01.2017 / 04:08

1 answer

3
  

The idea is that attributes in the Actions should override that defined in the Controller declaration, just like [AllowAnonymous] does perfectly.

Actually, that's not quite the way it is. [Authorize] is additive, so when you do:

[UserTypeAuthorize(TipoUsuario.Moderador)]
public ActionResult Edit(Guid id)
{ ... }

"Moderator" and "Administrator" are allowed to receive the Action result.

It has the same effect as this Action :

[UserTypeAuthorize(TipoUsuario.Administrador, TipoUsuario.Moderador)]
public ActionResult Edit(Guid id)
{ ... }

What you should do for this case is to give up using the Controller decoration . Use decor only for Actions , specifying which permissions can be used.

    
12.01.2017 / 05:20