user1284440
user1284440

Reputation: 41

.NET Session - Persist session, even when the user closes the browser

We use .net framework 3.5 and C#.

We have a site that requires the user to log in. So we use a database to check if the login / password is correct.

Then we make a call to FormsAuthentication.SetAuthCookie() , so the user we´´l be logged in my app.

And on all subsequent pages, we check with User.Identity.IsAuthenticated() if the user is logged in.

We want to preserve this session, even when the user closes the borwser.

How the best way to do this ?

We also have a problem with lost sessions, suddenly the user lost his authenticated status, I think that with that kind of new persist we can also solve that problem.

(sorry for my english..... portuguese speaker)

Upvotes: 4

Views: 7651

Answers (2)

usr-local-ΕΨΗΕΛΩΝ
usr-local-ΕΨΗΕΛΩΝ

Reputation: 26874

I would suggest a cleaner approach to store session information. Surely Shay's approach for persisting the authentication cookie is correct, but storing sessionState in process for long time has severe drawbacks when scaling the application to multiple concurrent users.

First, to clarify, session state means literally anything that you can access via Session[] collection.

A better technique, that I have seen successfully used* by a large bank, is to store persistent-session related information inside the database.

Basically you need

  1. A table that is primary and foreign keyed to the user ID, with a) as many columns as the variables you need to store or b) one single BLOB column containing the serialized value of the class
  2. A PersistentSession class
  3. Populate that object in Global.asax Session_Start or better Application_PostAuthenticateRequest method and save it in Session object
  4. Save the object from Session to DB in Global.asax Session_End method

If you chose approach B just serialize/deserialize the object and you got it!

*The real way the SAVESESSION was used by those guys is quite different

Upvotes: 1

Shay
Shay

Reputation: 353

You shouldn't mix terms, remember that you have both authentication cookie and session state in asp.net.

You appear to be looking for a persistent auth cookie. to have a persistent auth cookie try

FormsAuthentication.SetAuthCookie("xxx",true); 

http://msdn.microsoft.com/en-us/library/twk5762b(v=vs.90).aspx

passing true will allow the authentication cookie to survive browser restarts. also you should consider your timeout values for forms authentication and session in your web.config

<authentication mode="Forms">
        <!-- The name, protection, and path attributes must match 
       exactly in each Web.config file. -->
        <forms loginUrl="Default.aspx" name=".ASPXFORMSAUTH" protection="All" path="/" timeout="360"/>
    </authentication>

<sessionState mode="InProc" timeout="360" />

Upvotes: 6

Related Questions