asp.net程式開發,用戶根據角色訪問對應頁面以及功能。 項目結構如下圖: 根目錄 Web.config 代碼: admin文件夾中 Web.config 代碼: teacher文件夾中 Web.config 代碼: student文件夾中 Web.config 代碼: Login.aspx中登錄 ...
asp.net程式開發,用戶根據角色訪問對應頁面以及功能。
項目結構如下圖:
根目錄 Web.config 代碼:
1 <?xml version="1.0" encoding="utf-8"?> 2 <!-- 3 有關如何配置 ASP.NET 應用程式的詳細消息,請訪問 4 http://go.microsoft.com/fwlink/?LinkId=169433 5 --> 6 <configuration> 7 <system.web> 8 <compilation debug="true" targetFramework="4.0" /> 9 <authentication mode="Forms"> 10 <forms loginUrl="login.aspx"></forms> 11 </authentication> 12 <!--<authorization> 13 <allow users="*"></allow> 14 </authorization>--> 15 </system.web> 16 </configuration>
admin文件夾中 Web.config 代碼:
1 <?xml version="1.0"?> 2 <configuration> 3 <system.web> 4 <authorization> 5 <allow roles="admin" /> 6 <deny users="*"/> 7 </authorization> 8 </system.web> 9 </configuration>
teacher文件夾中 Web.config 代碼:
1 <?xml version="1.0"?> 2 <configuration> 3 <system.web> 4 <authorization> 5 <allow roles="teacher" /> 6 <deny users="*"/> 7 </authorization> 8 </system.web> 9 </configuration>
student文件夾中 Web.config 代碼:
1 <?xml version="1.0"?> 2 <configuration> 3 <system.web> 4 <authorization> 5 <allow roles="student" /> 6 <deny users="*"/> 7 </authorization> 8 </system.web> 9 </configuration>
Login.aspx中登錄成功後設置Cookie,設置Cookie代碼:
1 protected void SetLoginCookie(string username, string roles) 2 { 3 System.Web.Security.FormsAuthentication.SetAuthCookie(username, false); 4 System.Web.Security.FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddDays(1), false, roles, "/"); 5 string hashTicket = FormsAuthentication.Encrypt(ticket); 6 HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket); 7 HttpContext.Current.Response.SetCookie(userCookie); 8 }
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); //這樣當前用戶就擁有角色信息了 } } }