I have created my first uber small webapp with MVC4. So far I used the layout stuff to layout the webapp and added some views controllers and a model to register and allow users to log in.
Once a user logged in / registered, I store its username in the session. I read this property from the session to determine if a user has been logged in or not.
Is that a bad practice? I read a lot about RESTful and stateless webapps. I kinda get the feeling that I should not save anything in my session.
e.g.
@if (string.IsNullOrEmpty(Session["User"] as string))
{
<dl>
<dt><a href="/Account/Register">Register</a></dt>
<dt><a href="/Account/Login">Login</a></dt>
</dl>
}
else
{
<dl>
<dt><a href="/Account/ShowAccount/@Session["User"]">@Session["User"]</a></dt>
<dt><a href="/Account/Logout">Log out</a></dt>
</dl>
}
Q1: is this a bad practice?
Q2: is this "hack safe"? As is, is it easy to hack the current session and store a value in Session["User"] to bypass logging in?
To answer your questions:
1) In general, using session state is not bad practice, as long as you need it for your applications and you understand its implications on performance and scalability. However, in your case, if all you need to store is the user's name, then you really don't need it, if your application is using an ASP.Net membership provider, then this information is available in the User property in the MVCController base class:
var username = User.Identity.Name
There are three ways that session data can be stored: "InProc", where it is stored in the app process, "StateServer", where it is stored output process on a separate server, and "SQLServer", where it is stored in a SQL Server DB. Which one you should use depends upon if you are using a server farm, if your session needs to be durable (i.e. survive a machine reboot), and what the performance requirements are for your app (StateServer and SQLServer are less performant that InProc). More information can be found here
2) You should use SSL to protect your session data. The data sent over SSL (HTTPS) is fully encrypted, headers included (hence cookies). A good discussion on how to prevent session hijacking attacks is found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With