asp.net MVC2 初探三

如何实现基于角色的权限控制
[Authorize(Roles = "admin")]
标记的action只能是认证用户才能访问。
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                        1,
                        userName,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(20),
                         false,
                         "admin" //写入用户角色
                        );
                
                 string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                
                System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
在全局配置文件中加入以下代码
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
                HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
                 if (authCookie == null || authCookie.Value == "")
                {
                         return;
                }
                FormsAuthenticationTicket authTicket = null;
                 try
                {
                        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                }
                 catch
                {
                         return;
                }
                 string[] roles = authTicket.UserData.Split( new char[] { ';' });
                 if (Context.User != null)
                {
                        Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
                }
        }
ok,这样就能够实现角色权限的控制
相关文章
相关标签/搜索