public void Login(Account account) { MyIdentity myIdentity = new MyIdentity(); myIdentity.Init(account); var ticket = new FormsAuthenticationTicket( 1, myIdentity.Name, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), false, ArrToString(myIdentity.Role), FormsAuthentication.FormsCookiePath); // Encrypt the ticket var encTicket = FormsAuthentication.Encrypt(ticket); // Create the cookie var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)) { Expires = DateTime.Now.Add(FormsAuthentication.Timeout), }; HttpContext.Current.Response.Cookies.Add(authCookie); HttpContext.Current.User = new GenericPrincipal(myIdentity, myIdentity.Role); }
private static void OnAuthenticateRequest(object sender, EventArgs e) { var application = (HttpApplication)sender; var context = application.Context; if (context.User != null && context.User.Identity.IsAuthenticated) { return; } var cookieName = FormsAuthentication.FormsCookieName; var cookie = application.Request.Cookies[cookieName.ToUpper()]; if (cookie == null) { return; } try { var ticket = FormsAuthentication.Decrypt(cookie.Value); var identity = MyIdentity.Deserialize(ticket.UserData); var principal = new GenericPrincipal(identity, identity.Role); context.User = principal; Thread.CurrentPrincipal = principal; } catch (Exception ex) { Console.WriteLine(ex); } }