具有权限代码的ASP.NET MVC 4自定义授权属性(无角色)


121

我需要在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();
}

有可能这样做吗?

Answers:


243

我可以使用以下自定义属性来执行此操作。

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

我已经尝试过您的HandleUnauthorizedRequest示例,但是当我指定RouteValueDictionary时,它只是将不存在的路由重定向给我。它将我想要将用户重定向到的路由附加到用户想要访问的路由... si当我想要localhost:9999 / admin时,我得到了类似的信息:localhost:9999 / admin / Home
Marin 2014年

1
@Marin尝试在RouteValueDictionary中添加area = string.Empty
Alex

30
我正在投票,但是后来我看到“如果(条件){返回true;} else {返回false;}” ...
GabrielBB

1
@Emil我只是返回String.Contains方法给我的布尔值。但这无关紧要,我没有投票,只是没有投票呵呵。
GabrielBB

2
.Name.ToString()是多余的,因为Name属性已经是字符串
FindOutIslamNow '18

13

这是上一个的修改。回答。主要区别在于,当用户未通过身份验证时,它使用原始的“ 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);
        }
    }

3

也许这对将来的任何人都有用,我实现了一个自定义的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();
    }
}

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()
{....
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.