7

I have an app which uses Form's Authentication and when the user log's in, I retrieve the user's actual name and assign that to a session variable, like so:

[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            Session["Name"] = client.GetName(model.UserName);
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            return RedirectToAction("Index", "Home"); 
        }
    }
}

This is then displayed on my Index view, like so:

<h3>Welcome, @Session["Name"]</h3>

So if my name was Bob, it would output "Welcome, Bob" on my view and this works fine. But once I navigate away from the page or close my browser and return a few minutes later, it seems as if these Session variables have been destroyed as it just outputs "Welcome, " but I'm still logged in so my session isnt destroyed? I've set the session to be destroyed after 60 minutes in my web.config:

<sessionState regenerateExpiredSessionId="true" timeout="60" />

Edit

This only happens when I check my "Remember Me" box when logging in, as I guess this keeps a cookie client side so when I re-open my browser Im still logged in but a new session ID is created as I did a Response.Write(Session.SessionID) on my Index page and the ID before I closed my browser was different to the one when I re-opened it. If I don't check my "Remember Me" box then I'm forced to login again upon re-opening my browser

CallumVass
  • 11,288
  • 26
  • 84
  • 154

5 Answers5

5

I had the same problem with my session variables. If the remember me option was selected at the logon it would bypass my code to set the session variable I needed the next time the user would go to the site.

I was able to solve my issue by repopulating the session variable if the IsAuthenticated was true.

protected void Session_Start(object sender, EventArgs e)
{
    if (User.Identity.IsAuthenticated)
    {
        Session["Name"] = client.GetName(User.Identity.Name);   
    }
}
dklomparens
  • 66
  • 1
  • 2
  • this have to be a big warning on tutorials and manuals of Form's Authenticatio / membership on asp.net. thanks for point the best solution so far – FabianSilva Mar 14 '14 at 15:11
2

Instead of adding the name to a session variable, just change the following

FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

to

FormsAuthentication.SetAuthCookie(client.GetName(model.UserName), model.RememberMe);

You can then just use the User.Identity.Name instead of the @Session["Name"].

Remy
  • 232
  • 3
  • 11
0

The issue you have is with the line

FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

This is a cookie and last longer than sessions (depending on how long you set the forms timeout)

If all you need is to just display the username, you can use and just remove the session altogether

<h3>Welcome, @User.Identity.Name</h3>
Jason Jong
  • 4,310
  • 2
  • 25
  • 33
  • No, I need to display their real name, I knew I could use their username, but I wanted to display their real name. I've made the cookie expire after the same period in my web.config: ` – CallumVass Apr 12 '12 at 12:12
0
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); 

this code should work fine and you should be able to see "Welcome USERNAME", try to see that whether IE settings like tools-->internet options-->General tab delete my browsing history is checked or not. (on the same tab is you click on delete button you will see its clearing cookies also so that might be issue).

Cookies values will be retained if you close browser but not session(inproc) variables.

jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • But its not a cookie? Session state is held on the server isnt it? Also I don't want to display the Username as I've stated, thats why I use a method to retrieve the user's actual name and put that into a session variable – CallumVass Apr 12 '12 at 12:19
0

Maybe first check to ensure that a new session isn't started somehow. Place a breakpoint in the Session_Start in the global.asax.cs file:

protected void Session_Start(object sender, EventArgs e)
{
    var sessionId = Session.SessionID; // break here
}

It might seem silly but there are a couple of things that could actually cause a new session. Eliminating those will get you closer to a solution.

Closing your browser and opening it up again will probably cause a new session. Changes to the folder structure within your site and changes to the web.config will cause a new session (application pool will be recycled).

Eben Roux
  • 12,983
  • 2
  • 27
  • 48
  • My global.asax file doesnt have a Session_Start method – CallumVass Apr 13 '12 at 07:21
  • Right, instead of that, I did a response.write(session.sessionId) on my index page and the 2 session id's are different. – CallumVass Apr 13 '12 at 07:25
  • Once I've re-opened my browser, If I keep refreshing a new SessionID is generated each time? But If I log in and don't close my browser and then keep hitting refresh, I have the same SessionID – CallumVass Apr 13 '12 at 07:36
  • OK, so somehow your session is being restarted. Your browser cookies may be to blame here since typically a cookie is used to store the session id. – Eben Roux Apr 13 '12 at 07:54
  • Any idea on how I resolve this, otherwise my only option is to remove the remember me feature – CallumVass Apr 13 '12 at 08:52
  • I don't think removing the feature will solve your session problem. You are probably going to want your session *not* expire. Are your cookies enabled on your browser? – Eben Roux Apr 13 '12 at 09:37
  • Yea, if they weren't then it wouldnt keep me logged in once I have closed and re-opened the browser – CallumVass Apr 13 '12 at 09:50
  • Hang on, your issues isn't with the session expiring. Rather with getting the user name into the Session variable. You can use the session start event to do that. Find your user again and set the Session["Name"] or use a cookie to store the name. *lol* --- silly that I missed the point. – Eben Roux Apr 13 '12 at 10:52
  • Well, I have a basket which I use the session variable, along with the user's account number to retrieve the items in their basket. So new session == new basket – CallumVass Apr 13 '12 at 10:57
  • Hmm, this doesn't work either, it outputs blank info after moving it to the session start event, I noticed the session start event fired even before I had logged in – CallumVass Apr 13 '12 at 11:00
  • That's fine. But a new session means all you session contents are gone. So the Session["Name"] is gone that you set in the logon. You basically have to put that back when the session starts and you have the auth cookie. I don't use FormsAuthentication but if you can retrieve the user name use it to fetch the user from your data store and set the Session["Name'} again. – Eben Roux Apr 13 '12 at 11:00
  • The session start event *will* fire as soon as the session is created. Then you move on to other things like logging in, etc. That is why if you are remembered you can pick it up in the session start. – Eben Roux Apr 13 '12 at 11:01
  • Not if a new session ID is being created, like what's happening in my case at the moment? – CallumVass Apr 13 '12 at 21:20
  • I don't quite understand your question but since every session has a an ID a new session = new ID. – Eben Roux Apr 16 '12 at 04:08