给Asp.net MVC Forms 验证设置角色访问控制

  当我们使用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 应用 。 

posted @ 2013-03-05 16:18  记忆的森林  阅读(2329)  评论(1编辑  收藏  举报