示例#1
0
        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

            if (authCookie != null)
            {
                var authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                var serializer = new JavaScriptSerializer();

                var serializeModel = serializer.Deserialize<WebPrincipalSerializeModel>(authTicket.UserData);

                var newUser = new WebPrincipal(authTicket.Name)
                {
                    Id = serializeModel.Id,
                    SusbcriptionId = serializeModel.SusbcriptionId
                };

                HttpContext.Current.User = newUser;
            }
        }
示例#2
0
        public static bool Login(string email, string password, bool persistCookie = false)
        {
            bool success = System.Web.Security.Membership.ValidateUser(email, password);
            if (success)
            {
                var provider = System.Web.Security.Membership.Providers[Provider_Name] as WebMembershipProvider;

                if(provider == null)
                    throw new InvalidCastException(Provider_Name);

                var user = provider.GetUser(email);

                var serializeModel = new WebPrincipalSerializeModel
                {
                    Email = user.Email,
                    Id = user.Id,
                    SusbcriptionId = user.SubscriptionId
                };

                var serializer = new JavaScriptSerializer();
                var userData = serializer.Serialize(serializeModel);

                var expirationDate = DateTime.Now.Add(FormsAuthentication.Timeout);
                var authTicket = new FormsAuthenticationTicket(1, user.Email, DateTime.Now, expirationDate, persistCookie, userData);

                var encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                Response.Cookies.Add(cookie);

                //We add the custom principal here so it's available right after login.
                var newUser = new WebPrincipal(authTicket.Name)
                {
                    Id = serializeModel.Id,
                    SusbcriptionId = serializeModel.SusbcriptionId
                };

                HttpContext.Current.User = newUser;
            }

            return success;
        }