Example #1
0
        public void OnAuthenticateRequest(Object source, EventArgs e)
        {
            HttpApplication httpApp    = (HttpApplication)source;
            HttpCookie      authCookie = httpApp.Context.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket = null;
                try
                {
                    authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                }
                catch
                {
                    return;
                }

                if (authTicket.Expired)
                {
                    return;
                }
                FormsAuthenticationTicket newTicket = FormsAuthentication.RenewTicketIfOld(authTicket);

                //Generate User from ticket
                CustomPrincipalSerializeModel serializeModel = JsonConvert.DeserializeObject <CustomPrincipalSerializeModel>(newTicket.UserData);
                CustomPrincipal newUser = new CustomPrincipal(newTicket.Name);
                newUser.UserId = serializeModel.UserId;
                newUser.Roles  = serializeModel.Roles;

                HttpContext.Current.User = newUser;

                //If ticket was renewed set new ticket to cookie
                if (newTicket != authTicket)
                {
                    string     encTicket = FormsAuthentication.Encrypt(newTicket);
                    HttpCookie faCookie  = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                    httpApp.Context.Response.Cookies.Remove(authCookie.Name);
                    httpApp.Context.Response.Cookies.Add(faCookie);
                }
            }
        }
Example #2
0
        public static void AuthUser(HttpResponseBase response, string username, string id, string[] roles, bool remember)
        {
            CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();

            serializeModel.UserId = id;
            serializeModel.Roles  = roles;

            string userData = JsonConvert.SerializeObject(serializeModel);
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                1,
                username,
                DateTime.Now,
                DateTime.Now.AddHours(5),
                remember,
                userData
                );

            string     encTicket = FormsAuthentication.Encrypt(authTicket);
            HttpCookie faCookie  = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

            response.Cookies.Add(faCookie);
        }