当设置isPersistent=true 为持久化登陆时, 居然导致了身份认证信息设置失败.
不知道问题处在那儿.....
关键就是红色的设置哪里. 我查看了cookie也正确的.
如果注销了.则正常.
1 /// <summary> 2 /// 设置身份认证 3 /// </summary> 4 /// <param name="userData">用户</param> 5 /// <param name="sRole">角色</param> 6 /// <param name="expiration">过期时间</param> 7 /// <param name="isPersistent">是否持久cookie</param> 8 public static void SetFormsAuthentication(string userData, string sRole = "user", DateTime? expiration = null, 9 bool isPersistent = false) 10 { 11 if (HttpContext.Current == null) throw new InvalidOperationException(); 12 13 expiration = expiration ?? DateTime.Now.AddDays(1); 14 var ticket = new FormsAuthenticationTicket(2, userData, DateTime.Now, expiration.Value, isPersistent, sRole, 15 FormsAuthentication.FormsCookiePath); 16 17 var cookieValue = FormsAuthentication.Encrypt(ticket); 18 19 var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue); 20 21 if (ticket.IsPersistent) 22 { 23 cookie.Expires = ticket.Expiration; 24 } 25 26 HttpContext.Current.Response.Cookies.Add(cookie); 27 }
修改了一下 让cookie和和ticket过期一致的. 好像还没问题.
但是之前的身份丢失也是时有时无.... 怪哉...
还不放心. 继续测试....
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue) { Expires = ticket.Expiration, };
你可以试是这个FormsAuthentication.SetAuthCookie("username",IsPersistent: false);来快捷生成ticket,这种方法系统会自动新建一个cookies来保存ticket,并根据IsPersistent是否为true,以及webconfig中的timeout来确定cookies的到期时间。
你的第一种方法,无论自己把cookies的时间设置为多久,只要ticket.Expiration到期了,及时cookies还存在,用户验证依然会失败。
1. FormsAuthentication.SetAuthCookie 不能设置角色哦... 不能达到我的要求.
2.var ticket = new FormsAuthenticationTicket(2, userData, DateTime.Now, expiration.Value, isPersistent, sRole, 15 FormsAuthentication.FormsCookiePath);
ticket有设置过期时间的. cookie是要和ticket过期保存一致的.