ASP.NET MVC 4 自定义授权属性 - 如何将未经授权的用户重定向到错误页面? [英] ASP.NET MVC 4 custom Authorize attribute - How to redirect unauthorized users to error page?

查看:25
本文介绍了ASP.NET MVC 4 自定义授权属性 - 如何将未经授权的用户重定向到错误页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用自定义授权属性根据用户的权限级别授权用户访问.我需要将未经授权的用户(例如,用户尝试在没有删除访问级别的情况下删除发票)重定向到访问被拒绝的页面.

I'm using a custom authorize attribute to authorize users' access based on their permission levels. I need to redirect unauthorized users (eg. user tries to delete an invoice without Delete acess level) to access denied page.

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

The custom attribute is working. But in a case of unauthorized user access, nothing shown in the browser.

控制器代码.

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

感谢您能分享您的经验.

Appreciate if you can share your experience on this.

推荐答案

您必须按照指定覆盖 HandleUnauthorizedRequest 此处.

You have to override the HandleUnauthorizedRequest as specified here.

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

**注意:更新的条件语句 16 年 1 月

**Note: updated conditional statement Jan '16

这篇关于ASP.NET MVC 4 自定义授权属性 - 如何将未经授权的用户重定向到错误页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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