ASP.NET MVC 4 custom Authorize attribute - How to redirect unauthorized users to error page? [duplicate]

主宰稳场 提交于 2019-11-26 08:16:25

问题


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.

Contoller Code.

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

        return View();
    }

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

        return View();
    }

    // more codes/ methods etc.
}

Custom Attribute class code.

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.


回答1:


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

**Note: updated conditional statement Jan '16



来源:https://stackoverflow.com/questions/13284729/asp-net-mvc-4-custom-authorize-attribute-how-to-redirect-unauthorized-users-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!