简体   繁体   中英

ASP.NET Forms Authentication Expiry

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM