asp.net2.0用户角色安全问题

 1

这是Global.ascx中的代码
 2    protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
 3    { 
 4        if (HttpContext.Current.User != null)//如果当前的http信息中存在用户信息  
 5        { 
 6            if (HttpContext.Current.User.Identity.IsAuthenticated)//如果当前用户的身份已经通过了验证  
 7            { 
 8                if (HttpContext.Current.User.Identity is FormsIdentity) 
 9                { 
10                    //如果当前用户身份是FormsIdentity类即窗体验证类,此类有个属性能够访问当前用户的验证票  
11                    FormsIdentity fi = (FormsIdentity)HttpContext.Current.User.Identity;//创建个FormsIdentity类,用他来访问当前用户的验证票  
12                    //获得用户的验证票  
13                    FormsAuthenticationTicket ticket = fi.Ticket; 
14                    //从验证票中获得用户数据也就是角色数据  
15                    string userData = ticket.UserData; 
16                    //把用户数据用,分解成角色数组  
17                    string[] roles = userData.Split(','); 
18                    //重写当前用户信息,就是把角色信息也加入到用户信息中  
19                    HttpContext.Current.User = new GenericPrincipal(fi, roles); 
20
21                } 
22            } 
23        } 
24    } 
25

这里是登录模块的代码 

1protected void lblogin_Click(object sender, EventArgs e) 
 2    { 
 3        string uname=this.TextBox1.Text; 
 4        string pwd = this.TextBox2.Text; 
 5string roles = null; 
 6        bool check = RoleData.RoleControl(uname, pwd,out roles); 
 7if (check) 
 8
 9//创建一个新的验证票FormsAuthenticationTicket 
10FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 
111,//票版本号 
12uname,//用户名 
13DateTime.Now,//生成cookie时间 
14DateTime.Now.AddMinutes(20),//cookie的有效时间 
15false,//是不是永久存在的cookie 
16roles);//从数据库读到的用户角色数据 
17
18//把验证票加密 
19string hashTicket = FormsAuthentication.Encrypt(ticket); 
20
21//设置验证票cookie,第一个参数为cookie的名字,第二个参数为cookie的值也就是加密后的票 
22HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket); 
23//把cookie加进Response对象发生到客户端 
24//得到请求的url 
25Response.Cookies.Add(cookie); 
26string requestUrl = FormsAuthentication.GetRedirectUrl(FormsAuthentication.FormsCookieName, false); 
27
28//不要使用FormsAuthentication.RedirectFromLoginPage方法,因为这个方法会重写cookie 
29//重新定向到请求的url 
30if (requestUrl != null) 
31
32Response.Redirect(requestUrl); 
33
34else 
35
36Response.Redirect("index.aspx"); 
37
38
39else 
40
41this.lbcheck.Text = "用户名或者密码错误,请重试!"; 
42this.lbcheck.Visible = true; 
43
44    } 
45}

这里和大家分享和学习如何学IT!
原文地址:https://www.cnblogs.com/fuchifeng/p/1290786.html