我们来看下Forms身份验证基本原理:一 身份验证要采用Forms身份验证,先要在应用程序根目录中的Web.config中做相应的设置:<authentication mode="Forms"> <forms name=".ASPXAUTH" loginUrl="login.aspx" timeout="30" path="/"/></authentication>其中<authentication mode="Forms"> 表示本应用程序采用Forms验证方式。<forms>标签中的name表示指定要用于身份验证的Cookie。默认是.ASPXAUTH,其实你可以用任何名字,这也就是你在本地硬盘上看到的cookie里面的前面的几个字.Forms的验证过程如下:1,生成身份验证票,2,加密身份验证票.3,写回客户端,4,浏览器重新定向.其实这一系列的动作如果我们不用roles的话都是通过FormsAuthentication.RedirectFromLoginPage方法来完成了这一系列的工作任务.但是既然我们要使用roles授权,我们就不能够使用这个方法,而要分开来,一步步完成.首先是创建身份验证票,首先我们看看FormsAuthenticationTicket类的一个构造函数:public FormsAuthenticationTicket(int version, //设为1string name, //用户标示DateTime issueDate, //Cookie 的发出时间, 设置为 DateTime.Now DateTime expiration, //过期时间bool isPersistent, //是否持久性(根据需要设置,若是设置为持久性,在发出cookie时,cookie的Expires设置一定要设置)string userData, //这里用上面准备好的用逗号分割的role字符串string cookiePath // 设为”/”,这要同发出cookie的路径一致,因为刷新cookie要用这个路径);最后个参数可以省略FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket (1,”kent”,DateTime.Now, DateTime.Now.AddMinutes(30), false,UserRoles)
然后加密:
string hashTicket = FormsAuthentication.Encrypt(ticket);//设置验证票cookie,第一个参数为cookie的名字,第二个参数为cookie的值也就是加密后的票HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,hashTicket);//设置cookie的有效期是一个礼拜cookie.Expires = DateTime.Now.AddDays(7);//把cookie加进Response对象发生到客户端Response.Cookies.Add(cookie);//得到请求的urlstring requestUrl = FormsAuthentication.GetRedirectUrl(FormsAuthentication.FormsCookieName,false);//不要使用FormsAuthentication.RedirectFromLoginPage方法,因为这个方法会重写cookie//重新定向到请求的urlResponse.Redirect(requestUrl);
