日期:2014-05-20 浏览次数:20822 次
<authentication mode="Forms"> <forms protection="All" defaultUrl="ParentFrame/main.aspx" loginUrl="Login.aspx" name="UserCookie" timeout="3600"></forms> </authentication> <authorization> <deny users="?"></deny> </authorization> <!--以下为角色验证--> <location path="UserManage.aspx"> <system.web> <authorization> <allow roles="user"/> <deny users="*"/> </authorization> </system.web> </location> <location path="BackupManage.aspx"> <system.web> <authorization> <allow roles="backup"/> <deny users="*"/> </authorization> </system.web> </location>
protected void Image1_Click(object sender, ImageClickEventArgs e)//登录按钮 { if (Page.IsValid) { MyUser user = (MyUser)Session["User"]; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.U_Name, DateTime.Now, DateTime.Now.AddMinutes(30), false,user.U_Purview,"/"); string hashTicket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket); Context.Response.Cookies.Add(cookie); Response.Redirect("ParentFrame/main.aspx"); } } protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)//验证用户名或者密码是否正确 { DataSourceSelectArguments da = new DataSourceSelectArguments(); Sqldatasource1.SelectCommand = "SELECT U_ID, U_Name, U_Password, U_Enable, U_Type, U_Expires, U_mobile, U_Email, U_Purview, U_Remark FROM `user` WHERE (U_Name = '" + textfield.Value.Trim() + "') AND (U_Password = '" + textfield2.Value.Trim() + "') and (u_type = '系统用户')"; DataView dv = (DataView)Sqldatasource1.Select(da); if (dv.Count == 0) { args.IsValid = false; } else { //把登录的用户信息保存为session MyUser user = new MyUser(); DataTable dt = dv.Table; user.U_ID = (int)dt.Rows[0]["U_ID"]; user.U_Name = (string)dt.Rows[0]["U_Name"]; user.U_Password = (string)dt.Rows[0]["U_Password"]; user.U_Enable = (Boolean)dt.Rows[0]["U_Enable"]; user.U_Type = (string)dt.Rows[0]["U_Type"]; user.U_Expires = (DateTime)dt.Rows[0]["U_Expires"]; user.U_Mobile = (string)dt.Rows[0]["U_Mobile"]; user.U_Email = (string)dt.Rows[0]["U_Email"]; user.U_Purview = (string)dt.Rows[0]["U_Purview"]; user.U_Remark = (string)dt.Rows[0]["U_Remark"]; Session["User"] = user; args.IsValid = true; } } protected void Application_AuthorizeRequest(object sender, System.EventArgs e)//全局事件,把角色信息添加到GenericPrincipal中 { HttpApplication App = (HttpApplication)sender; HttpContext Ctx = App.Context; //获取本次Http请求相关的HttpContext对象 if (Ctx.Request.IsAuthenticated == true) //验证过的用户才进行role的处理 { FormsIdentity Id = (FormsIdentity)Ctx.User.Identity; FormsAuthenticationTicket Ticket = Id.Ticket; //取得身份验证票 string[] Roles = Ticket.UserData.Split(','); //将身份验证票中的role数据转成字符串数组 Ctx.User = new System.Security.Principal.GenericPrincipal(Id, Roles); //将原有的Identity加上角色信息新建一个GenericPrincipal表示当前用户,这样当前用户就拥有了role信息 } }