Search code examples
asp.netsessionvariablescachingviewstate

What are the pros and cons of using session variables to manage a users session data?


Using ASP.NET I have always used session variables to maintain a users session data.

Typically: (Coded as simple bools/ints with around 12 total variables)

  • User information.
  • Page security permissions.

I have read increasing information regarding the negative effects of using session variables. I am aware that session variables are stored in memory and the negative effects that using too many can have; this is not the desired scope of this question.


What I would like to know:

Using current development languages and features:

  • Do session variables pose a security risk? (By security risk I mean is it possible to read / alter variables)

  • Is there better performance using querystrings, viewstate, caching, or making database request on every page load?

  • What is "considered" good practice for handling a users session data. (All topics relating to this subject are now very old and perhaps no longer relevant)?


Solution

  • A performance is always something subjective and may vary depending on different things. In your case you're trying to compare incomparable because

    • querystrings cannot be used to share sensitive user information or page security, because everyone can modify urls directly in the browser
    • viewstate is set and maintained on the page level. It cannot be carried across different page requests, only on postbacks of the current page.
    • caching is done on the application level, and all users can access it. It might work in case of page security permissions but not applicable to store individual user information.

    Making database requests is the only comparable option and yes, it's slower than a session. This is where you can try to play with viewstate and caching and try improve performance and reduce a database workload.

    Sessions are stored in a memory on the server but depend on cookies and in theory, it's possible to hijack the session by stealing the asp.net session cookie.

    SessionID values are sent in clear text. A malicious user could get access to the session of another user by obtaining the SessionID value and including it in requests to the server. If you are storing sensitive information in session state, it is recommended that you use SSL to encrypt any communication between the browser and server that includes the SessionID value.

    Quote: http://msdn.microsoft.com/en-us/library/ms178581.aspx

    Bottom line: using sessions is secure but to make it more secure use HTTPS

    ASP.NET provides out of the box functionality for user authentication, role based authorization and user profiles which might make sense to use. Read more about profiles: How to use Profile in ASP.NET? and Regarding Profile and session in asp.net There is a lot of other topics and answers here on this site regarding authentication and authorization.