1

On a project I am currently working on I have three roles: Admin, Super-user and User.

Admins can delete users, delete comments etc, but Super-users must be able to delete comments too. So I built an AdminController and Authorized it with Admin. One method must be accessable with the Super-user, so I authorized it for the Super-user but that won't work.

[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
    (... here be only admin methods ...)

    [HttpGet]
    [Authorize(Roles = "Super-user")]
    public ActionResult Delete()
    {
        //deletes a comment
        return View();
    }

    (... here be only admin methods ...)
}

I looked into overriding the Authorize attribute but I'm trying to find a solution where that is not needed, any idea's on how to authorize just one method for the Super-user?

The Admin as the Super-user must have access to the method Delete().

Thanks!

tereško
  • 58,060
  • 25
  • 98
  • 150

1 Answers1

0

I think as @Felix Cen pointed specifying this should work at controller

[Authorize(Roles = "Admin, Super-user")]

and then specify this at the method level

[Authorize(Roles = "Super-user")]

Alternatively you can use a deny attribute as pointed out in this question

public class DenyAttribute : AuthorizeAttribute
{

    protected override bool AuthorizeCore(HttpContextBase httpContext) {
        if (httpContext == null) {
            throw new ArgumentNullException("httpContext");
        }

        IPrincipal user = httpContext.User;
        if (!user.Identity.IsAuthenticated) {
            return false;
        }

        if (Users.Length > 0 && Users.Split(',').Any( u => string.Compare( u.Trim(), user.Identity.Name, StringComparer.OrdinalIgnoreCase))) {
            return false;
        }

        if (Roles.Length > 0 && Roles.Split(',').Any( u => user.IsInRole(u.Trim()))) {
            return false;
        }

        return true;
    }

Another question here(i think that i sort of like this specific answer here)

My personal take on this would be to split the controller. Just create another controller For the actions you don't need authentication.

Or you could have :

BaseController
doesn't require authentication - here you have all your "base stuff" :).

BaseAuthController : BaseController
all actions here require authentication.

That way you can have authentication when you want , just by deriving from a specific class.

Community
  • 1
  • 1
maztt
  • 12,278
  • 21
  • 78
  • 153