asp.net程式中,使用者可以根據角色訪問對應頁面以及功能。本文將對此進行介紹,具有很好的參考價值,下面跟著小編一起來看下吧
asp.net程式開發,使用者根據角色訪問對應頁面以及功能。
項目結構如:
根目錄 Web.config 代碼:
<?xml version="1.0" encoding="utf-8"?><!-- 有關如何配置 ASP.NET 應用程式的詳細訊息,請訪問 http://www.php.cn/ --><configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> <authentication mode="Forms"> <forms loginUrl="login.aspx"></forms> </authentication> <!--<authorization> <allow users="*"></allow> </authorization>--> </system.web></configuration>
admin檔案夾中 Web.config 代碼:
<?xml version="1.0"?><configuration> <system.web> <authorization> <allow roles="admin" /> <deny users="*"/> </authorization> </system.web></configuration>
teacher檔案夾中 Web.config 代碼:
<?xml version="1.0"?><configuration> <system.web> <authorization> <allow roles="teacher" /> <deny users="*"/> </authorization> </system.web></configuration>
student檔案夾中 Web.config 代碼:
<?xml version="1.0"?><configuration> <system.web> <authorization> <allow roles="student" /> <deny users="*"/> </authorization> </system.web></configuration>
Login.aspx中登入成功後設定Cookie,設定Cookie代碼:
protected void SetLoginCookie(string username, string roles){System.Web.Security.FormsAuthentication.SetAuthCookie(username, false); System.Web.Security.FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddDays(1), false, roles, "/"); string hashTicket = FormsAuthentication.Encrypt(ticket); HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket); HttpContext.Current.Response.SetCookie(userCookie);}
Global.asax 中進行身分識別驗證:
protected void Application_AuthenticateRequest(object sender, EventArgs e){ HttpApplication app = (HttpApplication)sender; HttpContext ctx = app.Context; //擷取本次Http請求的HttpContext對象 if (ctx.User != null) { if (ctx.Request.IsAuthenticated == true) //驗證過的一般使用者才能進行角色驗證 { System.Web.Security.FormsIdentity fi = (System.Web.Security.FormsIdentity)ctx.User.Identity; System.Web.Security.FormsAuthenticationTicket ticket = fi.Ticket; //取得身分識別驗證票 string userData = ticket.UserData;//從UserData中恢複role資訊 string[] roles = userData.Split(','); //將角色資料轉成字串數組,得到相關的角色資訊 ctx.User = new System.Security.Principal.GenericPrincipal(fi, roles); //這樣目前使用者就擁有角色資訊了 } }}