c# - ASP.NET MVC Blacklist for Roles/Users -
question summary: in asp.net mvc, there clean way prevent specific user or role accessing action?
obviously, following allow roles admin
, editor
access entire controller.
[authorize(roles = "admin, editor")] public class homecontroller : controller { public actionresult index() { return view(); } public actionresult about() { return view(); } }
if wanted admin
role have access about
action, following:
[authorize(roles = "admin, editor")] public class homecontroller : controller { public actionresult index() { return view(); } [authorize(roles = "admin")] // take precedence on controller's authorization public actionresult about() { return view(); } }
is there way accomplish without listing every single role needs access, , specifying roles should prevented having access?
create own blacklist class one:
public class blacklist : authorizeattribute { private list<string> roleslist; public string roles { { string roles = ""; if (roleslist!= null && roleslist.count > 0) { int counter = 0; foreach (string role in roleslist) { counter++; if (counter == roleslist.count) roles = role; else roles += role + ","; } } return roles; } set { roleslist = new list<string>(); string[] roles = value.split(','); foreach (string role in roles) { roleslist.add(role); } } } //constructor public blacklist () { roleslist = new list<string>(); } protected override bool authorizecore(httpcontextbase httpcontext) { bool result = true; if (httpcontext == null) { throw new argumentnullexception("httpcontext"); } foreach (string role in roleslist) { if (httpcontext.user.isinrole(role)) { result = false; break; } } return result; } }
now going block roles want:
[authorize] [blacklist (roles = "admin", "editor")] public actionresult index() { return view(); }
Comments
Post a Comment