Authorizeattribute in Controlller and Actions

Asked

Viewed 198 times

3

When using an attribute (Authorizeattribute) developed by me (with use of Enums) it is not working as it should as follows:

When used to memorize the Controller statement:

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

It works normally as it should, but when using Actions within this same controller, as far as I know, I should overwrite the controller only in this Action in which it is decorated with its other Enums or with the use of the [Allowanonymous].

The idea is that attributes in Actions should override the one defined in the Controller statement, just as [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)
    { ... }
}

Meu 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.

1 answer

3


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

It’s not really like that. [Authorize] is additive, so when you do:

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

"Moderator" and "Administrator" are authorized to receive the result of Action.

It has the same effect as this other Action:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.