我写了一个例子程序.第一次使用基于Froms的验证.首先假设用户登陆成功(这个一般从数据库得到验证).
然后写入验证票据Authentication.以后的页面中判断这个用户是否通过验证,如果没有,重定向到用户登陆页面.如果已经登陆,则执行业务逻辑.本文重点在讨论Authentication在角色验证中的使用.对其他方面不与关注.
步骤如下:
一.在用户登陆按扭事件中加入以下代码:
这段代码主要是在用户登录后写入Cookie.
private void Button1_Click(object sender, System.EventArgs e)
{
string username=TextBox1.Text.Trim();
string roles="Admin";
//生成验证票据对象.
FormsAuthenticationTicket authTicket=new FormsAuthenticationTicket(
1,
username,
DateTime.Now,DateTime.Now.AddMinutes(20),
false,
roles);
//加密验证票
string encrytedTicket=FormsAuthentication.Encrypt(authTicket);
//生成Cookie对象.
//FormsAuthentication.FormsCookieName取得WebConfig中
1<authentication>
2//配置节中Name的值作为Cookie的名字.
3HttpCookie authCookie=new HttpCookie(FormsAuthentication.FormsCookieName,
4encrytedTicket);
5Response.Cookies.Add(authCookie);
6
7//跳转到用户的初试请求页.
8Response.Redirect(FormsAuthentication.GetRedirectUrl(username,false));
9
10}
11二.在Global.asax.cs 的Application_AuthenticateRequest事件中添加如下代码:
12//获取用户的角色。
13string cookieName=FormsAuthentication.FormsCookieName;//从验证票据获取Cookie的名字。
14
15//取得Cookie.
16HttpCookie authCookie=Context.Request.Cookies[cookieName];
17
18if(null == authCookie)
19{
20return;
21}
22FormsAuthenticationTicket authTicket = null;
23
24//获取验证票据。
25authTicket = FormsAuthentication.Decrypt(authCookie.Value);
26
27if(null == authTicket)
28{
29return;
30}
31
32//验证票据的UserData中存放的是用户角色信息。
33//UserData本来存放用户自定义信息。此处用来存放用户角色。
34string[] roles = authTicket.UserData.Split(new char[] {','});
35
36FormsIdentity id=new FormsIdentity(authTicket);
37
38GenericPrincipal principal=new GenericPrincipal(id,roles);
39
40//把生成的验证票信息和角色信息赋给当前用户.
41Context.User=principal;
42三.以后的各个页面中通过HttpContext.Current.User.Identity.Name判断用户标识,
43HttpContext.Current.User.IsInRole("Admin")判断用户是否属于某一角色(或某一组)
44
45四.WebConfig的修改:
46<authentication mode="Forms">
47<forms loginurl="LoginTest.aspx" name="MyAppFormsAuth" path="/" protection="All" timeout="20"></forms>
48</authentication>
49上面这段大家都明白的了,我不多说了.主要是下面这段配置.
50如果你在虚拟目录中有一个文件夹.这个文件夹只能由某些组访问.那么就可以向下面这样设置.
51<!-- 设置对本地目录的访问。如果验证票据未通过,则无法访问
52\-->
53<location path="Admin">
54<system.web>
55<authorization>
56<!-- Order and case are important below -->
57<allow roles="Admin"></allow>
58<deny users="*"></deny>
59</authorization>
60</system.web>
61</location>
62
63
64这样,你就可以使用基于角色的窗体身份验证了.
65我的一点浅见,共享出来,欢迎大家批评.</authentication>