In an ASP. NET program, users can access the corresponding pages and functions according to their roles. This article will be introduced, with a good reference value, follow the small series below to see it
ASP. NET program development, users access to the corresponding page and function according to role.
Project structure such as:
root directory Web. config code:
<?xml version= "1.0" encoding= "Utf-8"?><!--For more information about how to configure an ASP. NET application, please visit 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>
The Web. config code in the Admin folder:
<?xml version= "1.0"?><configuration> <system.web> <authorization> <allow roles= "admin"/ > <deny users= "*"/> </authorization> </system.web></configuration>
The Web. config code in the teacher folder:
<?xml version= "1.0"?><configuration> <system.web> <authorization> <allow roles= "Teacher" /> <deny users= "*"/> </authorization> </system.web></configuration>
The Web. config code in the Student folder:
<?xml version= "1.0"?><configuration> <system.web> <authorization> <allow roles= "Student" /> <deny users= "*"/> </authorization> </system.web></configuration>
Set cookies after successful login in Login.aspx, set cookie code:
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);}
Authentication in Global.asax:
protected void Application_AuthenticateRequest (object sender, EventArgs e) {HttpApplication app = (HttpApplication) Sender HttpContext CTX = App. Context; Gets the HttpContext object for this HTTP request if (CTX. User! = null) {if (ctx. request.isauthenticated = = true)//authenticated generic user for role validation {System.Web.Security.FormsIdentity fi = ( System.Web.Security.FormsIdentity) ctx. User.Identity; System.Web.Security.FormsAuthenticationTicket ticket = fi. Ticket; Get the authentication ticket string userData = ticket. userdata;//recover role information from UserData string[] roles = Userdata.split (', '); The role data is converted into a string array, and the relevant role information CTX is obtained . User = new System.Security.Principal.GenericPrincipal (FI, roles); So that the current user has role information}}}