public void AuthenticateRequestDecryptCustomFormsAuthenticationTicket(HttpContext httpContext) { UserData adminData; string formsCookieName = FormsAuthentication.FormsCookieName; HttpCookie httpCookie = httpContext.Request.Cookies[(String.IsNullOrWhiteSpace(formsCookieName)) ? Guid.NewGuid().ToString() : formsCookieName]; if (httpCookie == null) { adminData = new UserData(); } else { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(httpCookie.Value); if (!UserData.TryParse(ticket.UserData, out adminData)) { adminData = new UserData(); } string[] roles = null; if (adminData.IsSystemUser) { roles = new string[] { "Admin" }; } CustomPrincipal principal = new CustomPrincipal(new CustomIdentity(adminData.CredentialsId, adminData.UserName, adminData.FirstName, adminData.LastName, adminData.IsSystemUser), roles); httpContext.User = principal; Thread.CurrentPrincipal = principal; } }
internal static bool TryParse(string data, out UserData adminData) { if (string.IsNullOrWhiteSpace(data)) { throw new ArgumentNullException("data"); } adminData = null; string[] segments = data.Split(new string[] { Delimeter }, StringSplitOptions.RemoveEmptyEntries); if (segments.Length > 5) { return false; } adminData = new UserData() { CredentialsId = int.Parse(segments[0]), UserName = segments[1], IsSystemUser = bool.Parse(segments[2]), FirstName = (segments.Length > 3) ? segments[3] : null, LastName = (segments.Length > 4) ? segments[4] : null, }; return true; }
public void SignIn(int adminId, string userName, string firstName, string lastName, bool isSystemUser, System.Web.HttpResponseBase httpResponseBase) { UserData adminData = new UserData { CredentialsId = adminId, UserName = userName, LastName = lastName, FirstName = firstName, IsSystemUser = isSystemUser }; string encodedTicket = FormsAuthentication.Encrypt( new FormsAuthenticationTicket( version: 1, name: userName, issueDate: DateTime.UtcNow, expiration: DateTime.UtcNow.Add(FormsAuthentication.Timeout), isPersistent: true, userData: adminData.ToString()) ); HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encodedTicket); httpResponseBase.Cookies.Add(httpCookie); }