Search code examples
c#asp.net-mvc-3sessionsession-variablessqlmembershipprovider

confused on sessions and authentication


I am using Session to store a few values and it works fine. When these values are null I need to handle this. Usually they values are set at the login page when they first visit the site.

1.. Do I need to check the authentication to see if session has expired?

What confused me was this post: How to Check whether Session is Expired or not in asp.net

The replies are using Session and IsAuthenticated for the same purposes.

2.. Does Authentication use Session or are they one in the same?

3.. Does the SessionId expire or change for that browser window?

I did notice that the SessionId is created when they open a browser page, at least I am assuming this. So, please correct me if I am wrong.

4.. Do I check to see if they are authenticated for means of checking to see if my Session variables are still valid?

This is what I came up with for each controller method that I want to check to see if the Session variable is valid AND if they are authenticated:

  if (!HttpContext.User.Identity.IsAuthenticated)
  {
    Logging.WriteLog("User.Identity.Authenticated returned false");
    return RedirectToAction("Logon", "Account");
    //return View("Logon");
  }

5.. Do I have the right idea?

Please clear some of this up for me!


Solution

  • ASP.NET Session is based on a unique user/browser id and it is set in a cookie. The session should be valid throughout the whole browsing session of the user. When the user closes the browser, that cookie is removed, and the session is over. It is separate from any authentication you are using - though you can certainly set/remove values during the authentication process.