[MVC學習心得]如何自訂Authorize

在MVC的 Action方法可以冠上Authorize的Attribute,並可以指定授權角色,來驗證使用者是否有權限執行 如:[Authorize(Roles="Admin")]
但若要動態指定Roles時,會出現訊息 "錯誤 2 屬性引數必須是常數運算式、typeof 運算式或屬性參數型別的陣列建立運算式"
程式如下:
[Authorize(Roles=staticClass.GetCurrentRole())]
Ps:staticClass.GetCurrentRole()),此方法是在依照DB的資料來指定權限 

若想依照
DB的資料來判斷權限,可以參考如下

1.新增一類別並繼承AuthorizeAttribute 並新增一自訂屬性PrgNo

public class MyCustomAuthorizeAttribute : AuthorizeAttribute 
 
 
    /// <summary> 
      /// 程式編號 
      /// </summary> 
      public string PrgNo 
      { 
          get; 
          set; 
      } 
}

2.覆寫AuthorizeCore方法


protected override bool AuthorizeCore(HttpContextBase httpContext) 
 { 
            if (httpContext == null) 
                throw new ArgumentNullException("httpContext"); 
 
            string[] users = Users.Split(','); 
 
            if (!httpContext.User.Identity.IsAuthenticated) 
                return false; 
 
            //取得使用者的角色 
            FormsIdentity id = httpContext.User.Identity as FormsIdentity; 
            FormsAuthenticationTicket ticket = id.Ticket; 
            string[] currentRoles = ticket.UserData.Split(','); 
            string roles = this.GetRolesByPrg();//取得程式允許的角色 
 
            foreach (string role in currentRoles) 
            { 
                if (roles.IndexOf(role) > -1) 
                    return true; 
            } 
            return false; 
  } 
 
        /// <summary> 
        /// 依照程式編號取得授權角色 
        /// </summary> 
        /// <returns></returns> 
        string GetRolesByPrg() 
        ...{ 
            //testing code 不重要 
            //TODO:DB 邏輯  
            return "Admin,Manager"; 
        }


3.在Action冠上自訂的AuthorizeAttribute


[MyCustomAuthorize(PrgNo="Kim110")] 
public System.Web.Mvc.ActionResult Index() 
{ 
  var result = this._productDAL.GetAllProducts(); 
  return View(result); 
}


大功告成這樣就可以明確的指定Action對應到程式編號可以有哪些角色可以使用


範例檔案
MyCustomAuthorizeAttribute.zip


MDSN
http://social.msdn.microsoft.com/Forums/zh-TW/236/thread/9b646099-67d8-4e42-b7b9-e2ba66e5a40d
參考文章
http://schotime.net/blog/index.php/2009/02/17/custom-authorization-with-aspnet-mvc/

這個網誌中的熱門文章

IIS 設定只允許特定IP進入