日期:2014-05-17  浏览次数:20448 次

为何使用FormsAuthenticationTicket保存用户身份票据无效






我知道
FormsAuthentication.SetAuthCookie("AAA", false);
可以将用户AAA的身份票据保存到Cookie,那么下次页面回发时AAA将作为已登录的用户,使用User.Identity.IsAuthenticated会返回true

但是我看到网上有人说可自己手动制造用户身份票据的的Cookie并保存到Cookie中,这可以代替FormsAuthentication.SetAuthCookie方法

代码如下
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1,
                    "AAA",
                    DateTime.Now,
                    DateTime.Now.Add(FormsAuthentication.Timeout),
                    false,
                    null
                    );

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,FormsAuthentication.Encrypt(ticket));

Response.Cookies.Add(cookie);
但是我执行上面代码后发现Cookie .ASPXAUTH倒是在Request.Cookies中存在了,但是使用User.Identity.IsAuthenticated还是返回false,而且User.Identity.Name是空字符串,说明AAA没有通过身份验证,请问这是为什么?

------解决方案--------------------
asp.net FORM认证
------解决方案--------------------
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];  
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(new char[]{';'});
Context.User = new GenericPrincipal(Context.User.Identity, Roles); 

Response.Redirect(FormsAuthentication.GetRedirectUrl()); 
asp.net FORM认证