C # .net - authentication expiring prematurely

I create a cookie for authentication in C # as persistent and with an end date of one year from now, but expires too long after it is set. Code below ...

DateTime endDate = new DateTime();
endDate = DateTime.Now.AddYears(1);

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                                                            username,
                                                            DateTime.Now,
                                                            endDate, 
                                                            true, 
                                                            userId.ToString(),
                                                            FormsAuthentication.FormsCookiePath);


string encryptedTicket = FormsAuthentication.Encrypt(ticket);

HttpCookie authCookie = new HttpCookie(
                       FormsAuthentication.FormsCookieName,
                       encryptedTicket);

authCookie.Expires = endDate;

Response.Cookies.Add(authCookie);

Any ideas?

+3
source share
1 answer

I realized this ... when I checked if the user was authenticated, I used the following code ...

if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
{
     return true;
}

when I deleted the first check (i.e.HttpContext.Current.User! = null), it started working. Although I really don't understand how HttpContext.Current.User.Identity.IsAuthenticated can be true if HttpContext.Current.User is null.

In any case, it works now, so no problem.

+3

Source: https://habr.com/ru/post/1726056/


All Articles