否认自定义角色 [英] deny custom role

查看:131
本文介绍了否认自定义角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能拒绝访问调用方法。像这样

  [的HandleError]
    [授权(角色=基于role1,role2所)]
    公共类AdminController:控制器
    {
        [拒绝(角色=role2所)]
        公众的ActionResult ResultPage(字符串消息)
        {
            计算机[消息] =消息;
            返回查看();
        }
}


解决方案

您可以简单地做它周围的其他方法,并检查role1上的presence而不是基于role2缺席的。另外,您可以开发自己的DenyAttribute,你想要做什么,验证用户是不是在指定的角色。

  [的HandleError]
[授权(角色=基于role1,role2所)]
公共类AdminController:控制器
{
    [授权(角色=role1上)]
    公众的ActionResult ResultPage(字符串消息)
    {
        计算机[消息] =消息;
        返回查看();
    }
}公共类DenyAttribute:AuthorizeAttribute
{    保护覆盖布尔AuthorizeCore(HttpContextBase HttpContext的){
        如果(HttpContext的== NULL){
            抛出新的ArgumentNullException(HttpContext的);
        }        IPrincipal的用户= HttpContext.User中;
        如果(!user.Identity.IsAuthenticated){
            返回false;
        }        如果(Users.Length大于0&放大器;&放大器; Users.Split(,)任何(U =>的String.Compare(u.Trim(),user.Identity.Name,StringComparer.OrdinalIgnoreCase))){
            返回false;
        }        如果(Roles.Length大于0&放大器;&放大器; Roles.Split(,)任何(U => user.IsInRole(u.Trim()))){
            返回false;
        }        返回true;
    }}

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

解决方案

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

}

这篇关于否认自定义角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆