給Asp.net MVC Forms 驗證設定角色存取控制

來源:互聯網
上載者:User

  當我們使用Asp.net MVC Forms方式驗證使用者, 然後設定Controller 或 Action 的 Authorize屬性時, 預設情況下只有Users屬性可以設定(這裡的Users通常是指使用者登入名稱), 我們無法直接設定使用者的角色資訊 , 當建立一個依賴角色的應用時(又不想麻煩配置Membership),我們有必要給認證使用者加上角色資訊,下面是具體方法 :

1.Web.config 配置 ,以下設定標明我們使用Forms驗證 , 所有沒有授權的使用者無法訪問帶Authorize標記的 Controllers 和 Actions

<system.web>

<authentication mode="Forms"><forms loginUrl="~/Account/LogOn" timeout="2880" cookieless="UseCookies" path="/" name=".ASPXAUTH" /></authentication><authorization><deny users="?"/></authorization></system.web>

2 Global.asax.cs 添加驗證請求事件代碼 ,如果使用者資訊已經設定, 則重新構造帶角色資訊的使用者物件 , 角色資訊從身份憑證票據的UserData屬性中擷取,多個角色以逗號隔開。

 protected void Application_AuthenticateRequest(object sender, EventArgs e)        {            var app = sender as HttpApplication;            if (app.Context.User!=null)            {                var user = app.Context.User;                var identity = user.Identity as FormsIdentity;                // We could explicitly construct an Principal object with roles info using System.Security.Principal.GenericPrincipal                var principalWithRoles = new GenericPrincipal(identity, identity.Ticket.UserData.Split(','));                // Replace the user object                app.Context.User = principalWithRoles;                           }        }

預設情況下角色資訊是空的,如:

替換後, 如 :

 

3.使用者合法性驗證通過後, 構造帶角色資訊的加密身份憑據 , 角色資訊儲存在票據的UserData中。 

        [HttpPost]        public ActionResult LogOn(User user)        {            // check user by quering database or other ways. skip this logic.            string userRoles = "admin,user,powerUser";            bool isPersistent = true;            int version = 0;            double persistentMinutes = 60.00; // minutes            string userName = user.Name;            string cookiePath = FormsAuthentication.FormsCookiePath;            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(version, userName, DateTime.Now, DateTime.Now.AddMinutes(persistentMinutes), isPersistent, userRoles, cookiePath);            string encryptedTicket = FormsAuthentication.Encrypt(ticket);            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);            Response.Cookies.Add(cookie);            return Redirect(Request.QueryString["returnUrl"]);        }

4. 使用角色資訊控制使用者對Controller 或 Action 的訪問 , 因為我們上面設定使用者擁有admin , user , powerUser 角色, 所以使用者有權訪問此方法

 public class HomeController : Controller    {        [Authorize(Roles="admin,powerUser")]        public ActionResult Index()        {            //使用者擁有 admin,user,powerUser 角色, 所以可以訪問此方法。            return View();        }    }

5. 以下是AuthorizeAttribute AuthorizeCore方法的源碼 , 我們可以看到其中只要使用者有AuthorizeAttribute.Roles設定中的任意角色, 就可以通過AuthorizeAttribute 的審核

  // This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.        protected virtual bool AuthorizeCore(HttpContextBase httpContext)        {            if (httpContext == null)            {                throw new ArgumentNullException("httpContext");            }            IPrincipal user = httpContext.User;            if (!user.Identity.IsAuthenticated)            {                return false;            }            if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))            {                return false;            }            if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole))            {                return false;            }            return true;        }

以上同樣適用於 Asp.net WebForms 應用 。 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.