我需要在我的MVC 4应用程序中根据用户权限级别(没有角色,只分配给用户的CRUD操作级别的权限级别)来控制对视图的访问。
作为一个例子; AuthorizeUser下面将是我的自定义属性,我需要像这样使用它:
[AuthorizeUser(AccessLevels="Read Invoice, Update Invoice")]
public ActionResult UpdateInvoice(int invoiceId)
{
// some code...
return View();
}
[AuthorizeUser(AccessLevels="Create Invoice")]
public ActionResult CreateNewInvoice()
{
// some code...
return View();
}
[AuthorizeUser(AccessLevels="Delete Invoice")]
public ActionResult DeleteInvoice(int invoiceId)
{
// some code...
return View();
}
有可能这样做吗?
答案 0 :(得分:230)
我可以使用自定义属性执行此操作,如下所示。
[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewInvoice()
{
//...
return View();
}
自定义属性类如下。
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);
}
}
您可以通过覆盖AuthorisationAttribute
方法在自定义HandleUnauthorizedRequest
中重定向未经授权的用户:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Error",
action = "Unauthorised"
})
);
}
答案 1 :(得分:12)
以下是对prev的修改。回答。主要区别在于当用户未经过身份验证时,它使用原始" HandleUnauthorizedRequest"重定向到登录页面的方法:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated) {
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Account",
action = "Unauthorised"
})
);
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
答案 2 :(得分:1)
也许这对将来的任何人都有用,我已经实现了一个自定义的Authorize Attribute,如下所示:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class ClaimAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
private readonly string _claim;
public ClaimAuthorizeAttribute(string Claim)
{
_claim = Claim;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var user = context.HttpContext.User;
if(user.Identity.IsAuthenticated && user.HasClaim(ClaimTypes.Name, _claim))
{
return;
}
context.Result = new ForbidResult();
}
}
答案 3 :(得分:0)
如果您将WEB API与Claims一起使用,则可以使用以下方法:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AutorizeCompanyAttribute: AuthorizationFilterAttribute
{
public string Company { get; set; }
public override void OnAuthorization(HttpActionContext actionContext)
{
var claims = ((ClaimsIdentity)Thread.CurrentPrincipal.Identity);
var claim = claims.Claims.Where(x => x.Type == "Company").FirstOrDefault();
string privilegeLevels = string.Join("", claim.Value);
if (privilegeLevels.Contains(this.Company)==false)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Usuario de Empresa No Autorizado");
}
}
}
[HttpGet]
[AutorizeCompany(Company = "MyCompany")]
[Authorize(Roles ="SuperAdmin")]
public IEnumerable MyAction()
{....
}