FormsAuthenticationTicket

244 阅读1分钟

构建基于forms的验证机制过程如下: 
1,设置IIS为可匿名访问和asp.net web.config中设置为form验证 
2,检索数据存储验证用户,并检索角色(如果不是基于角色可不用) 
3,使用FormsAuthenticationTicket创建一个Cookie并回发到客户端,并存储 
角色到票据中,如: 
FormsAuthentication.SetAuthCookie(Username,true | false) 
cookies保存时间: 
HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName].Expires=DateTime.Now.AddDays(1) 

如果需要存储角色,采用: 
FormsAuthenticationTicket authTicket = new 
FormsAuthenticationTicket( 
1, // 版本号。 
txtUserName.Text, // 与身份验证票关联的用户名。 
DateTime.Now, // Cookie 的发出时间。 
DateTime.Now.AddMinutes(20),// Cookie 的到期日期。 
false, // 如果 Cookie 是持久的,为 true;否则为 false。 
roles ); // 将存储在 Cookie 中的用户定义数据。 
roles是一个角色字符串数组 
string encryptedTicket = FormsAuthentication.Encrypt(authTicket); //加密 

存入Cookie 
HttpCookie authCookie = 
new HttpCookie(FormsAuthentication.FormsCookieName, 
encryptedTicket); 

Response.Cookies.Add(authCookie);