加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-4 – ASP.NET MVC 4自定义权限属性 – 如何将未经授

发布时间:2020-12-16 00:37:18 所属栏目:asp.Net 来源:网络整理
导读:参见英文答案 ASP.NET MVC – How to show unauthorized error on login page?7个答案我正在使用自定义授权属性来授权用户根据权限级别进行访问。我需要重定向未经授权的用户(例如,用户尝试删除没有删除访问级别的发票)来访问被拒绝的页面。 自定义属性正在
参见英文答案 > ASP.NET MVC – How to show unauthorized error on login page?7个答案我正在使用自定义授权属性来授权用户根据权限级别进行访问。我需要重定向未经授权的用户(例如,用户尝试删除没有删除访问级别的发票)来访问被拒绝的页面。

自定义属性正在工作。但是在未经授权的用户访问的情况下,浏览器中没有显示任何内容。

Contoller代码。

public class InvoiceController : Controller
{
    [AuthorizeUser(AccessLevel = "Create")]
    public ActionResult CreateNewInvoice()
    {
        //...

        return View();
    }

    [AuthorizeUser(AccessLevel = "Delete")]
    public ActionResult DeleteInvoice(...)
    {
        //...

        return View();
    }

    // more codes/ methods etc.
}

自定义属性类代码。

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        string privilegeLevels = string.Join("",GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB

        if (privilegeLevels.Contains(this.AccessLevel))
        {
            return true;
        }
        else
        {
            return false;
        }            
    }
}

感谢您能分享您的经验。

解决方法

您必须按照 here规定覆盖HandleUnauthorizedRequest。
public class CustomAuthorize: AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if(!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(filterContext);
}
else
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new{ controller = "Error",action = "AccessDenied" }));
}
}
}

**注意:更新的条件语句Jan ’16

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读