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

浙公网安备 33010602011771号