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