1.You must change your web system to windows form authentication in web.config
- <authentication mode="Forms">
- <forms loginUrl="Pub/Login.aspx" name=".ASPXAUTH"></forms>
- </authentication>
2. Create a new web.config file under the folder you want to protect.
- <?xml version="1.0"?>
- <configuration>
- <appSettings/>
- <connectionStrings/>
- <system.web>
- <authorization>
- <!--多个角色用,分隔-->
- <allow roles="SuperAdmin,Admin"/>
- <deny users="*" />
- </authorization>
- </system.web>
- </configuration>
- <!--也可控制某个页的权限
- <location path="AnnounceList.aspx">
- <system.web>
- <authorization>
- <allow roles="admin"/>
- <deny users="*" />
- </authorization>
- </system.web>
- </location>
- <location path="ConfigInfo.aspx">
- <system.web>
- <authorization>
- <allow roles="users"/>
- <deny users="*" />
- </authorization>
- </system.web>
- </location>
- -->
Please be care of the under path for the location nodes. It should be under <configuration> node.
In the Login.aspx page,
the code should be like this,
- protected void Button1_Click(object sender, EventArgs e)
- {
- string username = UserLogin(TextBox1.Text);
- if (username != null && username != "")
- {
- string userRole = GetUserRole(username);
- SetLoginCookie(username, userRole);
- Response.Redirect("~//highlevel//high.aspx");
- }
- else
- {
- ltError.Text = "用户名输入错误!请重新输入!";
- }
- }
- public static void SetLoginCookie(string username, string roles)
- {
- //建立身份验证票对象
- FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(30), false, roles, "/");
- //加密序列化验证票为字符串
- string hashTicket = FormsAuthentication.Encrypt(ticket);
- HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
- HttpContext.Current.Response.Cookies.Add(userCookie);
- }
Create Global.asax at the root folder.
- 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); //这样当前用户就拥有角色信息了
- }
- }
- }
then the user can't visit the page without the right role. You must assure every person should have correct role.