ASP.NET Forms身份認證
更新時間:2017年02月07日 09:21:53 作者:《一個好人》
asp.net程序中,用戶可以根據角色訪問對應頁面以及功能。本文將對此進行介紹,具有很好的參考價值,下面跟著小編一起來看下吧
asp.net程序開發(fā),用戶根據角色訪問對應頁面以及功能。
項目結構如下圖:
根目錄 Web.config 代碼:
<?xml version="1.0" encoding="utf-8"?> <!-- 有關如何配置 ASP.NET 應用程序的詳細消息,請訪問 http://go.microsoft.com/fwlink/?LinkId=169433 --> <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); //這樣當前用戶就擁有角色信息了 } } }
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關文章
Entity Framework使用DbModelBuilder API創(chuàng)建表結構
這篇文章介紹了Entity Framework使用DbModelBuilder API創(chuàng)建表結構的方法,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-03-03.Net?Core?使用?TagProvider?與?Enricher?豐富日志的操作代碼
這篇文章主要介紹了.Net?Core?使用?TagProvider?與?Enricher?豐富日志的操作,本文通過示例代碼給大家介紹的非常詳細,需要的朋友可以參考下2024-03-03.Net?Core應用增強型跨平臺串口類庫CustomSerialPort()詳解
本文詳細講解了.Net?Core應用增強型跨平臺串口類庫CustomSerialPort(),文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-01-01