How to Make Session in ASP.Net MVC but not expired? - asp.net-mvc

var user=Db.GetUser();
Session["User"]=user;
var user=Session["user"] as List<User>;

I can assume you are looking for session expiration time.
This is a link to HttpSessionState collection
And you can change the time through your code as well:
Session.Timeout = 200; //in minutes
BTW: more information about sessions
Regarding the comments, max time cannot be more than 525600 minutes, so:
Session.Timeout = 525600;
Or through web config (that is easy BTW) as mentioned in the links
But you have to take into account that then all session will be in the server memory at some point IIS will recycle the app pool. And you will lose all sessions, even the active one. And moreover, you will face huge performance issues as well.
I would not recommend keeping the session long. You just check if session expired then call DB again.

Related

SessionState in ASP.NET MVC Application

I have an ASP.NET MVC application. I have the following:
<sessionState timeout="60" />
My question is that if a user goes on a page and takes more than 60 minutes to fill out all the fields on the page, will that constitute a timeout? What constitutes a timeout? Does a user need to go through different pages so timeout will not happen?
Simple answer is - Yes, a person taking more than the timeout (60 minutes in your example) on the same page would cause a timeout.
Session is server side, so if no requests are sent to the server for the timeout period - the session will expire and all the saved session variables will be lost.
To complicate things a little bit, if your page is making AJAX calls to the server - those could keep the session alive without navigating to a different page.
session data is stored for 60 minutes from the last request. So, if you access a page and something is stored as session data for you, it will be automatically removed after 60 minutes unless you have made a new request within this time period.
you shouldn't try to use sessions to store data for long periods of time.

Very simple authentication using Session in asp.net MVC - is this secure?

ASP.NET Identity is extremely complex and overkill for what I need in an ASP.NET MVC 5 app. Keeping things simple is a good principle IMHO.
When a user logs in I simply use Dapper to lookup email & password in the database (hashing & salting used).
Then I set a session["userID"] = user.Id // from database.
This Id is a high entropy randomly generated string (ie a security stamp that could be revoked - not the actual user ID), and the session timeout is set to a long time - eg 1 month - so users don't have to keep logging in.
Where a user is an administrator I also just set Session["admin"] = true;
I then create a simple class that inherits from AuthorizeAttribute:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.Session["userID"] == null)
return false;
else
return true;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectResult("~/Account/Login");
}
}
so I can use authorization attributes on my controllers:
[MyAuthorize]
public ActionResult MyController()
{
...
}
Is this secure? Are there any steps I am missing to secure this - if so what?
Is something so wrong with this it will fail in operation?
Is session capable of doing this? If not what is & what would be a better way (that is just as simple)?
First of all I don't agree with your comments about complexity. So far ASP.Net Identity is the most comprehensive and well-composed authentication/authorisation framework for .Net. It is superior to all predecessors with a lot of possible extensibility points. If you think this is very complex, then think of a security in general - it is a very complex domain with high risks involved. Identity framework actually simplifies and hides a lot of complexity so you don't have to deal with this. If you still insist this is complex... well, yes, software development is a complex business. Computing in general is complex... well, life is complex!
Anyway, back to your solution. I can see at least one major flaw with your solution. You keep your users authenticated by session cookie. You propose the session to be a very long lived. This means that session cookie is not changed for a long time. So in case somebody have managed to gain access to the session somehow, they will have a very long window of opportunity to abuse the access to your system as somebody else.
Identity solves this problem by rotating the cookie - by default every 30 minutes the auth cookie value is changed. So if you get somebody's yesterday cookie value - it won't be any good. You can also reduce this value to couple minutes or even make the cookie value update on every request.
Then you'll need to think about session expiry and management. First this will be a memory hog - for every user logged in the last 30 days you'll have to maintain a live session on your server. Imagine a thousand users logged on... I don't know how much data you'll have per user session, but given enough use you'll start hitting memory problems. Then if you would want to load-balance your servers, you'll have to introduce a sticky session. Also when your server restarts, all your users will loose their sessions (I've used this kind of system - it is horrid).
Next thing you'll have to take care of multiple user logins - what will happen when the same user logs in from 2 different browsers? What happens to user sessions when user changes password - how does it log out other browsers?
I've not done a terrible amount of work with session, so I'm not sure how session cookie is created. But looking on documentation (Session Identifiers section) sessionId is stored in the cookie. And you propose to put User.Id into that session cookie. That means that if User.Id is known to an attacker, then they can log in as that user any time they like. To mitigate that you'll have to come up with the way to hide user id inside the session and use some sort of correlation id, and even then you are not escaping the fact that once created correlation id will last entire session life - 30 days. Talking about complex solution?
Identity provides you a lot of functionality out of the box. Things that you probably won't need now but might in the future. And with home-grown solution this will be a case of writing this yourself.
Validate newly registered emails
2-Factor Authentication
Social logins
Password strength requirements
Username/email uniqueness requirement
User Lockout
Mitigate password sharing
Password reset through email link
List is not exhaustive - just something from top of my head.

ASP.net MVC 4 session cookie expires when user closes browser

I had the same issue like this guy. Because I am lucky, his solution also worked for me.
But I think it's a bit dirty and I was wondering if there isn't a better one.
I've set up this configuration on IIS, but the cookies will always expire when the user closes her browser (if I don't use he "cookie hack")
Any Ideas?
EDIT: To clearify: It not the Server side session that is lost, it's only the "ASP.NET_SessionId" cookie lifetime, which is incorrect.
EDIT2: After some Research, I was wondering when the ASP.NET_SessionId cookie is actually set. If I delete it (using Firefox) and refreshing the page (even several times) a new one won't appear ... What's going on here?
EDIT3: I just found out, that the session id cookie will be set if I put something into the session, so that question (EDIT2) is off.
The session cookie will exire as soon as possible for security reasons. One should not extent it's lifetime due to session hijacking.
If you need "the old session back", then use ASP.NET authentication and generate a new session after the users comes back to the site. This will safe memory and also increase overall security.

What is the lifespan of each data storage area in ASP .net MVC

I've seen some explanations of these, but nothing that really compares where they start, end, or overlap, or good examples of their use.
What is the life span of each of the following data collections? And am I missing any?
Application
Session
ViewData
TempData
application: as long as your application is running. your application may be automatically shutdown and restarted by the server for various reasons
session: as long as the user is actively using your site. this is generally determined by cookies that ASP.NET sends down to give each user a unique ID that expires after a while. there are lots of ways to customize & tweak this to meet various needs
viewdata: as long as the current request is being processed. this is used for sending data from a controller to a view for immediate rendering and thus not persisted
tempdata: until the value is read back out OR until the end of processing the next request in the session OR when the session ends/expires - whichever is sooner. this is meant to be used for moving data from one controller to another when you are issuing a Redirect
Application : This get initiated at the time when an application start and end when the application stops the execution.If user leaves the application domain or application gets restarted then also the application based data is lost.
Session : This is application based storage. This ends when user leaves the current request or the session get expired. It can be stored in several modes like application cookie or client side cookie.
ViewBag & ViewData : This storage method hold the data for the current request. It transport the data between view and controller.
TempData : Lifespan of this storage type depends on, at which request the Tempdata is read. Once it is read by program it gets destroyed. But we can increase its lifespan using peek or keep methods.

asp.net mvc storing user data

how should I store user data in asp.net mvc? Let's say a user want to see 50 records per page. I wanted to save it in Session, but if I am doing it right, the Session resets every time a new controller is initialized. So where? A cookie?
Typically the session is not reset on controller initialization! Make sure you aren't clearing the session from code.
Anyway, storing this in session cause the record-limit to be reset quite often (depend on the session timeout param).
Consider storing this in the user's profile kept in database (will be used after log in), or in cookie (don't require login to be used). This will keep this setting forever - your users will appreciate that :)
Instead of using the built in ProfileProvider-system in ASP.NET, which you should only use i you want to persist user settings across multiple visits, you could instead put a the settingsdata in the session. Maybe wrapped in a serializable object.
Session is cleared if
you clear it in your code
the cookie storing the sessionid expires (depends on your settings i web.config) (if a
cookie expires during a session, it does not truly expire before the user closes all browser windows)
if the application is restarted (unless you use sticky sessions (DB based sessions) in which case sessiondata persists through application restart)
Session does not reset when a new controller is initialized. But it does when you leave the application (your session ends) or the application is restarted. You should use Profile to store this kind of information.
See this:
http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx
http://www.odetocode.com/articles/440.aspx

Resources