views:

429

answers:

3

Hi

I am wondering how do I set a timeout for a user if they don't do any requests after say 10mins there session is killed and they are logged out.

I have in my webconfig this

<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn"
                   protection="All"
                   timeout="20160"
                   path="/"
                   requireSSL="false"
                   slidingExpiration="false"
                   defaultUrl="default.aspx"
                   cookieless="UseDeviceProfile"
                   enableCrossAppRedirects="false" />
</authentication>

I was told to set timeout to equal "20160" because I wanted to be logged in for 2 weeks if they checked the "stay logged in for 2 weeks". I also make sure to enable IsPersistent in my cookie Cookie.

So is there another timeout I need to set? Since after a certain time of inactivity on my site it does not work anymore. I have not timed it but say if I leave and come back 10mins later and try to do something on my site like saving something it won't work. So it looks like my connection was killed or something. I have to signout, log back in and then it works

Edit

This is how I make my cookie

 FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(version,userName,DateTime.UtcNow,DateTime.UtcNow.AddDays(14),createPersistentCookie,userData,"/");
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            authCookie.Path = "/";
            if (createPersistentCookie == true)
            {
                authCookie.Expires = DateTime.UtcNow.AddDays(14);
            }
            HttpContext.Current.Response.Cookies.Add(authCookie);

When I do set session state in my webconfig my url has this in it

(S(gkvkze55zfzzee45wj34byee))

I rather not have this nasty line in my code.

+2  A: 

I assume that your Timeout is caused by Session Timeout instead of Authentication Timeout

Check the session state node in your web.config.

<sessionState mode="InProc"
                    cookieless="true"
                    timeout="60"/>
Rasik Jain
I don't have session state in my webconfig. What does it default to?
chobo2
"Session" was mentioned in your question. thats what i was referring to <sessionstate/> attribute.
Rasik Jain
I was not aware that there was a seperate one for session state. I thought thats what the formAuth took care off.
chobo2
Check "DateTime.Now.AddMinutes(30), // expiration" when you create your formsauth ticket.FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // version txtEmail.Text, // name DateTime.Now, // issueDate DateTime.Now.AddMinutes(30), // expiration false, // isPersistent roles, // userData FormsAuthentication.FormsCookiePath // cookiePath );http://weblogs.asp.net/owscott/archive/2006/07/15/forms-authentication-timeout.aspx
Rasik Jain
The default session timeout is 10 minutes. http://msdn.microsoft.com/en-us/library/ms525473.aspx
David Stratton
Why does it not redirect them to like login page after they timeout?
chobo2
I also noticed when I add the sessionState in my webconfi it starts adding weird things to my URL what I don't like at all.
chobo2
Chobo2, I only think of <SessionState/>, <authentication/> for the timeouts. Not sure why its not working in your case..Also, Can you try to check how your forms auth cookie is created, I mean Are you setting expiration properly.Please check the link I have provided in my earlier comments, may be that will help..Any experts out there to suggest other approach...Thanks
Rasik Jain
@Rasik see my edit to see what I have.
chobo2
A: 

You can't have both sliding and absolute expiration of your forms authentication ticket.

See my answer to this SO question for an overview and links to tutorials to understanding Forms Authentication in ASP.NET.

Update:

how do I set a timeout for a user if they don't do any requests after say 10mins there session is killed and they are logged out

Logged Out = Forms Authentication and is orthogonal to Session (State) (e.g. the place to store data).

The simple answer is don't store data in sessions. See this SO question which seems similar to what you want.

Robert Paulson
Sorry I don't follow(Or I don't think I do). I don't have a sliding expiry date set. I just have an absolute expiration that either will be end of session or 2 weeks from login date.
chobo2
I've updated my answer with another link to another answer about ASP.NET and sessions / authentication. Please read the referenced info, especially the links and tutorial video's.
Robert Paulson
I put it on sliding now but it still will not keep me logged in for 2 weeks. I am not sure why.
chobo2
@chobo2, you can't have sliding and say "but only for 2 weeks max". Also, are you closing your browser? If you don't have the authentication cookie set to be persistent, the cookie itself will not be saved to disk, so you will not be logged in when you reopen your browser. See also msdn: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.slidingexpiration.aspx
Robert Paulson
A: 

Another answer, just to show how you might want to create your cookie using the values from the web.config instead of hardcoding them in code.

First off, consider if you need all the extra options. The simplest is to have everything setup in your web.config

FormsAuthentication.RedirectFromLoginPage("Bob", isPersistent)

However, if you need to add UserData to the ticket, you will have to create your own. Note how we use the values in the web.config instead of hard coding values.

/// <summary>
/// Create a New Forms Authentication Ticket when User Impersonation is active, using the current ticket as a basis for the new ticket.
/// </summary>
private static void NewTicket(MyUser currentUser, 
                              string userData, 
                              bool createPersistentCookie)
{
    System.Web.Configuration.AuthenticationSection authSection =
        (System.Web.Configuration.AuthenticationSection)
        ConfigurationManager.GetSection("system.web/authentication");

    System.Web.Configuration.FormsAuthenticationConfiguration 
        formsAuthenticationSection = authSection.Forms;

    DateTime now = DateTime.Now;

    // see http://msdn.microsoft.com/en-us/library/kybcs83h.aspx
    // Create a new ticket used for authentication
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        2,                                          // Ticket version
        currentUser.UserName,                       // Username to be associated with this ticket
        now,                                        // Date/time issued
        now.Add(formsAuthenticationSection.Timeout),// Date/time to expire
        createPersistentCookie,
        userData,
        FormsAuthentication.FormsCookiePath);

    // Hash the cookie for transport over the wire
    string hash = FormsAuthentication.Encrypt(ticket);
    HttpCookie cookie = new HttpCookie(
        FormsAuthentication.FormsCookieName,    // Name of auth cookie (specified in web.config)
        hash);                                  // Hashed ticket

    // Add the cookie to the list for outbound response
    HttpContext.Current.Response.Cookies.Add(cookie);
}

You can use the same technique for recreating the ticket while the user is already logged in. An example is if you needed to change the Ticket.UserData. When issuing a new ticket you would increment the version number.

Robert Paulson