ASP.NET MVC 4 権限コードを使用したカスタム承認属性(ロールなし) 質問する

ASP.NET MVC 4 権限コードを使用したカスタム承認属性(ロールなし) 質問する

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

このようにすることは可能ですか?

ベストアンサー1

次のようにカスタム属性を使用してこれを実行できます。

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

おすすめ記事