Beispiel #1
0
        public void SlideExpirationIfValidTicket()
        {
            if (HttpContext.Current == null)
            {
                return;
            }

            var httpContext = new HttpContextWrapper(HttpContext.Current);
            var log         = _logProvider.GetLogger(GetType().Name);

            // if there is already a new value for cookie present in the response, skip the operation
            if (httpContext.Response.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName))
            {
                return;
            }

            var ticket = TicketUtility.GetExistingTicket(httpContext);

            if (ticket == null)
            {
                return;
            }

            // if ticket has expired, lets do some housekeeping and remove it from cookies
            if (ticket.Expired)
            {
                log.Trace(() => $"Found expired ticket, removing it.");
                TicketUtility.AddToResponseCookie(null, httpContext);
                return;
            }

            log.Trace(() => $"Found valid existing ticket with expiration: {ticket.Expiration.ToString("s")}");

            var ageLeft = ticket.Expiration - DateTime.Now;

            // do nothing if half of timeout has not yet passed
            if (ageLeft.TotalSeconds > TicketUtility.TicketTimeout.Value.TotalSeconds / 2)
            {
                return;
            }

            log.Trace(() => $"Cookie age left is {ageLeft.TotalMinutes:0} minutes, refreshing expiration.");
            var newTicket = new FormsAuthenticationTicket(
                ticket.Version,
                ticket.Name,
                ticket.IssueDate,
                DateTime.Now + TicketUtility.TicketTimeout.Value,
                false,
                ticket.UserData,
                ticket.CookiePath);

            TicketUtility.AddToResponseCookie(newTicket, httpContext);
        }
        private FormsAuthenticationTicket GetOrCreateTicket()
        {
            var actualUserName = GetActualUserName();

            var existingTicket = TicketUtility.GetExistingTicket(_httpContextAccessor.HttpContext);

            if (existingTicket != null && IsTicketValid(existingTicket))
            {
                return(existingTicket);
            }

            // ticket not found or not valid, we will create a fresh one
            return(new FormsAuthenticationTicket(2, actualUserName, DateTime.Now, DateTime.Now + TicketUtility.TicketTimeout.Value, false, null));
        }