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,這樣就能夠實現角色權限的控制
相關文章
相關標籤/搜索