Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
        }
}
like image 307
kusanagi Avatar asked Feb 25 '26 13:02

kusanagi


1 Answers

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

}
like image 141
tvanfosson Avatar answered Feb 27 '26 03:02

tvanfosson