deny custom role

牧云@^-^@ 提交于 2019-12-07 16:02:15

问题


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:


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

}


来源:https://stackoverflow.com/questions/2682545/deny-custom-role

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!