我写了一个例子程序.第一次使用基于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中<Authentication> //配置节中Name的值作为Cookie的名字. HttpCookie authCookie=new HttpCookie(FormsAuthentication.FormsCookieName, encrytedTicket); Response.Cookies.Add(authCookie); //跳转到用户的初试请求页. Response.Redirect(FormsAuthentication.GetRedirectUrl(username,false)); } 二.在Global.asax.cs 的Application_AuthenticateRequest事件中添加如下代码: //获取用户的角色。 string cookieName=FormsAuthentication.FormsCookieName;//从验证票据获取Cookie的名字。 //取得Cookie. HttpCookie authCookie=Context.Request.Cookies[cookieName];
if(null == authCookie) { return; } FormsAuthenticationTicket authTicket = null; //获取验证票据。 authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if(null == authTicket) { return; }
//验证票据的UserData中存放的是用户角色信息。 //UserData本来存放用户自定义信息。此处用来存放用户角色。 string[] roles = authTicket.UserData.Split(new char[] {','});
FormsIdentity id=new FormsIdentity(authTicket);
GenericPrincipal principal=new GenericPrincipal(id,roles);
//把生成的验证票信息和角色信息赋给当前用户. Context.User=principal; 三.以后的各个页面中通过HttpContext.Current.User.Identity.Name判断用户标识, HttpContext.Current.User.IsInRole("Admin")判断用户是否属于某一角色(或某一组)
四.WebConfig的修改: <authentication mode="Forms" > <forms name="MyAppFormsAuth" loginUrl="LoginTest.aspx" protection="All" timeout="20" path="/"></forms> </authentication> 上面这段大家都明白的了,我不多说了.主要是下面这段配置. 如果你在虚拟目录中有一个文件夹.这个文件夹只能由某些组访问.那么就可以向下面这样设置. <!-- 设置对本地目录的访问。如果验证票据未通过,则无法访问 --> <location path="Admin"> <system.web> <authorization> <!-- Order and case are important below --> <allow roles="Admin"/> <deny users="*"/> </authorization> </system.web> </location>
这样,你就可以使用基于角色的窗体身份验证了. 我的一点浅见,共享出来,欢迎大家批评. 
|