I could do this with a custom attribute as follows.
[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewInvoice()
{
//...
return View();
}
Custom Attribute class as follows.
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
return privilegeLevels.Contains(this.AccessLevel);
}
}
You can redirect an unauthorised user in your custom AuthorisationAttribute
by overriding the HandleUnauthorizedRequest
method:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Error",
action = "Unauthorised"
})
);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…