Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Forms Authentication Expiry

Tags:

c#

asp.net

Can someone explain to me how ASP.NET Forms Authentication works because I don't seem to get it and I keep getting signed out.

As it stands, I have username, password and a "Keep me signed in" checkbox. From these values I'm creating a ticket and cookie, as follows:

    // Create ticket
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,email,DateTime.UtcNow,DateTime.UtcNow.AddMinutes(30),remember,String.Empty);

    // Encrypt ticket
    string cookie_contents = FormsAuthentication.Encrypt(ticket);

    // Create cookie
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,cookie_contents);

    if (remember) {
        cookie.Expires = DateTime.UtcNow.AddDays(90);
    }

    cookie.Path = FormsAuthentication.FormsCookiePath;
    cookie.Secure = true;

    // Add cookie to response
    Response.Cookies.Add(cookie); 

I would expect with this code that I can sign in to my website and assuming I check "Keep me signed in" that I stay signed in, for at least 90 days?

However what I am seeing is that I'm being signed out at least 30 minutes after initial login (which is the time set aside for the ticket?).

What is the difference between cookie expiration and ticket expiration and how do I keep myself signed. Do I need to set 90 days to both cookie and ticket?

like image 525
Lloyd Avatar asked Nov 13 '12 22:11

Lloyd


1 Answers

Don't manipulate the cookie directly if you can avoid it. You can use FormsAuthentication.SetAuthCookie(username, persistent) to sign a user in. Persistent here means "don't use session cookie".

You should then specify the cookie expiry in web.config under

 <system.web>
   <authentication mode="Forms">
             <forms timeout="50000000" slidingExpiration="true"/>
   </authentication>
 </system.web>

where sliding expiration means that the cookie will be renewed for each request. Timeout is in minutes, so the example is pretty high :)

Take a look at this question and the link to Scott Gu's blog: Forms Authentication Cookie Expiration

like image 113
faester Avatar answered Nov 07 '22 17:11

faester