views:

18

answers:

1
+1  Q: 

deny custom role

how can i deny access to call method. something like this

    [HandleError]
    [Authorize(Roles = "role1, role2")]
    public class AdminController : Controller
    {          


        [Deny(Roles = "role2")]
        public ActionResult ResultPage(string message)
        {
            ViewData["message"] = message;
            return View();
        }
}
+1  A: 

You could simply do it the other way around and check for the presence of role1 instead of the absence of role2. Alternatively you could develop your own DenyAttribute that does what you want and verifies that the user is not in the specified role.

[HandleError]
[Authorize(Roles = "role1, role2")]
public class AdminController : Controller
{          


    [Authorize(Roles = "role1")]
    public ActionResult ResultPage(string message)
    {
        ViewData["message"] = message;
        return View();
    }
}

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;
    }

}
tvanfosson
I really wish they had made the `_usersSplit` and `_rolesSplit` variables protected instead of private. You'd be able to reuse them instead of reimplementing the splitting.
tvanfosson