好的,这是我的代码创建一个认证cookie:
// get user's role List<UserType> roles = rc.rolesRepository.GetUserRoles(rc.userLoginRepository.GetUserID(userName)); List<string> rolesList = (from r in roles select r.ToString()).ToList(); string[] rolesArr = rolesList.ToArray(); // create encryption cookie FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1,userName,DateTime.Now,DateTime.Now.AddDays(90),createPersistentCookie,String.Join(";",rolesArr) //user's roles ); // add cookie to response stream string encryptedTicket = FormsAuthentication.Encrypt(authTicket); System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName,encryptedTicket); System.Web.HttpContext.Current.Response.Cookies.Add(authCookie); //FormsAuthentication.SetAuthCookie(userName,createPersistentCookie);
以下是我在Global.asax中的代码,将用户角色设置为用户身份:
protected void Application_AuthenticateRequest(Object sender,EventArgs e) { HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie == null || authCookie.Value == "") { return; } FormsAuthenticationTicket authTicket = null; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); string[] roles = authTicket.UserData.Split(new char[] { ';' }); if (Context.User != null) { Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity,roles); } } catch { return; } }
但是,如果顶部示例中的“createPersistentCookie”为TRUE,则不会创建持久性cookie.如果我删除最后一行如下所示:
//System.Web.HttpContext.Current.Response.Cookies.Add(authCookie); FormsAuthentication.SetAuthCookie(userName,createPersistentCookie);
那么在我的硬盘驱动器上创建持久性cookie.但是在Global.asax代码中,“authTicket”中的UserData字段为空,因此我无法正确设置角色!
所以我必须使用SetAuthCookie创建一个持久的cookie,但是由于某些原因,UserData字段从持久性cookie中消失.
这是什么答案?