Deny user role
1 answer
You could just do it the other way around and check for the presence of role1 instead of the absence of role2. Alternatively, you can develop your own DenyAttribute that does what you want and check 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;
}
}
+3
a source to share