deny custom role
how can i deny access to call method. something like this
[HandleError]
[Authorize(Roles = "role1, role2")]
public class AdminControlle开发者_开发技巧r : Controller
{
[Deny(Roles = "role2")]
public ActionResult ResultPage(string message)
{
ViewData["message"] = message;
return View();
}
}
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;
}
}
精彩评论