I have a basic Authentication system on my Asp.net MVC Website
[HttpPost]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
WebSecurity.Login(model.UserName, model.Password, persistCookie: false)
return RedirectToAction("Index", "Home");
}
I also have a UserInfoViewModel class where i keep some user specific information, and i use it on different pages.
To avoid creating the UserInfoViewModel every time i need it, i want to save it in Session on Login method.
public ActionResult Login(LoginViewModel model, string returnUrl)
{
WebSecurity.Login(model.UserName, model.Password, persistCookie: false)
var userInfoViewModel = new UserInfoViewModel();
Session["userInfo"] = userInfoViewModel;
return RedirectToLocal(returnUrl);
}
Considering that i have sensitive information that i rely on inside UserInfoViewModel, like IsSuperuser, is it safe to keep that object in Session? Will it expire when the user login session expires as well?
SOLUTION
System.Security.Principal.IIdentity is exacly made for that. It saves inside AUTH cookie custom user information you need, so you don’t recalculate it every time.
Use Custom Principal Objects video turorial
Thank you for answers!
Yes, it is safe because the Session is stored on the server. But you have another problem you should be thinking about if you decide to use ASP.NET Sessions. If this session is stored in the memory of the web server (default), IIS could recycle your application at any time and you will loose this session data. On the other hand the user will still be authenticated because he is tracked by a forms authentication cookie which will still be sent. So if you want to use Sessions I would recommend you switching to an out-of-proc session provider (such as
StateServerorSQLServer).Also as @Mikeb is pointing out in the comments section there’s another very serious issue with the Session. If you enabled it for read and write mode for a given controller you will not be able to process multiple requests from the same session in parallel. The server will block and process them sequentially. Think for example multiple AJAX requests from the same session. They will all block and process sequentially.