more persistent than session? - asp.net

we have a asp.net application which use session (in-proc) for single user across pages, now they want to keep the data (eg. a shopping cart) more persistent, even they leave the web app, means close the browser, next time they login use same id, they want the data back, any solution in ASP.NET?
If we save session in sql-server which I think is an option by microsoft, but I am not sure if it works even after user leave the app, or close the browser

Session data is meant to only persist for the lifetime of that browser session.
The answer is to not save the data in session, save it in the database in ShoppingCart and ShoppingCartItem tables instead. These will persist as long as you want them to.
The ShoppingCart table would have a UserID column that is FK to your User table.

You'll need to construct a relational database and store the entries in there.
Granted, the Application scope is higher than Session, but it will only exist for the life of the application pool. It sounds like you're looking for permanent storage.

I've seen shopping cart system using cookies instead and some using both cookies and database.
Cookie only: The "official" size of a cookie is 4K
Cookie + database: Store a GUID in the cookie and use it as a reference in the database
But... I think that storing shopping cart in a cookie or a cookie/database is not very user friendly. I do prefer that the website forget my shopping cart if I leave. I'm annoyed when website store such information with my approval.

You will need to use a database to mirror the data contained in the session, that way the data will persist long after the user logs off, if the application is restarted, or if the server is restarted. You could save the session object into sql-server as a binary object and serialize/deserialize when needed, but how do you know when to do the initial serialization? It's hard to tell when a user has logged off if they close the browser window.
Storing the session object as a single column might work in the interim, but in the long run you will probably want to come up with a proper relational design and store data in columns in tables, that way you can run queries and reports against the "work-in-progress" shopping carts (such as: how long do people let a shopping cart sit before finally checking out?).
As others have mentioned, cookies are another option but those exist on the client side, and if they decide to clear cookies (a lot of tech support people seem to give this advice as the first response when users complain about slow browsers), the shopping cart is lost.

Related

Get users security and info every request -> Else data gets stale

What we have currently implemented works well but I'm just concerned that there maybe a better way or we are doing it completely wrong.
Once logged into our website, on each and every request it will make a request to the API to get the users details.
E.g. Username, ImageUrl, Roles / Permissions, Email Address etc
It then stores this data in the BaseController for the viewpage or anyone else to see during that request.
Upside:
to doing it this way is that you know each request that the users permissions/roles and their details are all up to date!
Downside:
Your most likely to get exactly the same data every request, until that one day they change their details. Thus your possibly making unnecessary calls??
However the first way we tried all this was when the user logged in all their data gets stored in the cookie, the problem with this is that our users hardly ever logout so all the data that is stored in the cookie gets stale often. -> Stale Roles/Permissions is an annoying issue!!!
How does everyone get around the stale data from login.
I would go back to your initial approach of storing the claims inside the cookie.
If you do indeed have very long log in times then I would guard against stagnant claims by periodically refreshing the cookie.
If you are using forms authentication then you could intercept the FormsAuthentication_OnAuthenticate event in Global.asax, decrypt and manage the cookie (here), validate the user and cookie first then run a quick conditional check against a custom field in the userdata property, called refreshedDate.
If the last refresh date or creation date is greater than some configurable window then call to the database and refresh the claim data from the database. Finally update the refreshDate and claim data and update the cookie.
Update
Following on from your comment...
Just to say that it is not uncommon to hit the database for each request, that is to say I have known it happen in a number of production systems. Many people are probably using ASP.NET session state using MS-SQL database's. Typically I have seen it when there is a real security need to invalidate someone's session, deny access and log them out immediately.
If your database is on the network locally to your web servers and/or latency is acceptably low then it can be a perfectly workable solution. Just make sure your database queries are minimal and performance tuned to perfection, consider side steeping any ORM (if applicable) and use raw SQL connections to make things as fast a possible.
If database latency is high, the other middle ground solution is caching, using Redis or Memcached to house the results of your queries and invalidating the cache when permissions are altered etc... but obviously adding the required infrastructure and operational support for caching solutions is a serious consideration.
You can apply an expiration to the cookie; that way it dies and requires them to login. Or, keep their user ID in the cookie, but store their profile info in session. When session dies, the next time the profile is checked if it is null, make a query to the API again. This way, it's getting updated more frequently.
In addition to other suggestions, another option may be to use a notification mechanism from the underlying role/permission store whenever a user's data changes. This notification could then be used to invalidate the cached data on the web server. This would ensure that the cached data is returned in the majority cases but the store would then be hit only when the data had changed.
If the underlying datastore is SQL Serevr then consider something like SqlDependency.
This is obviously a more complex architecture but it would meet your requirement and only you could say whether it's worth the effort / complexity / tradeoff!

ASP.NET Session Management - User Decides Cookies Or HttpSessionState

I am working on a small web application right now and part of the requirements is to allow the user to pick how their session will be managed: with either cookies or HttpSessionState. I have researched how to use cookies (http://www.codeproject.com/Articles/31914/Beginner-s-Guide-To-ASP-NET-Cookies) and Sessions (http://msdn.microsoft.com/en-us/library/ms178581(v=vs.100).aspx). I will be using non-persistent cookies.
The application will collect some data about the user (name, age, school) and take this session data and display messages on another page depending on the data that the user entered.
The thing I am having problems with is how to deal with how the user will pick the management. That information is also part of the session! The selection will be checked on every page on the web application.
I have researched globals (http://www.dotnetperls.com/global-variables-aspnet) but that is not a good method because it can be shared among different users which is not what I want! Correct me if I am wrong. How can I store this data temporarily through the session without actually using a session or a cookie?
Is it even possible to do this with cookies and sessions being mutually exclusive?
At the end of the day, you should save it somewhere. This option if it is not persistent, as it may be asked/changed by every time user visits the web site, the easiest way is to save it in a hidden html field. As user submits the forms, the value will be passed to the next page if you are using html forms. Or you can retrieve the value and send it manually in asp.net (e.g. Transfer).
You may use ViewState (not recommended) as well. If the information should be persister for future, try using User Profiles in ASP.net and save it as a custom field in database. This one is really cumbersome.

ASP.NET session id shared amongst browser tabs

I've recently been developing a website using asp.net webforms that uses in proc sessions and I noticed that session ids are shared amongst browser tabs. So I was wondering what you would do for the following situations:
Problem:
Multiple logins with different users in the one browser problem
User opens browser tab 1, logins
with "user1" - store in
session
User opens browser tab 2, logins with "user2" - store in session
At this stage session information is now pointing to "user2" because of how session id is shared amongst browser
tabs
User tries an action on tab 1 and suddenly they have "user2"
information
How do you alert the user in tab 1 that the user has changed or how do force tab1 user to logout?
My initial thought was to keep a list of active users with session id via database or application object, but the problem I face is that in tab 1 what am I going to compare the list against, when I do a request the HttpContext.Current.User would be updated with "user2" how do I know browser tab 1 was initially for "user1"
Appreciate anyone letting me know of any alternatives or best practices for the above problem
Regards DotnetShadow
Why don't you warn when user2 logs in instead? With a message like "You are already logged in as user1, are you sure you want to login again as another user?"
All tabs in a browser belong to the same instance, so all tabs share cookies and sessions, there isnt much you can do about it. If you want to implement this badly the only solution that comes to mind is carrying a unique session id with each URL. Based on that unique id you can link a specific user. You will need customize the session logic and would have to make sure all links in your website carry this unique id. It could be done with alot of effort but the real question is , is it worth doing?
Some have suggested adding uniquifiers into the URL, and tracking based on those.
If you're going to do this, you may as well just let ASP.Net do this for you by turning on cookieless sessions - it then uses the URL to contain the session ID.
That's just how it is. You can't do much about it. Users are now accustomed to this behavior as it is consistent among famous internet sites like gmail, etc... so it shouldn't be much of a problem to them.
What I do to avoid this problem is redirect to append a short, random in-url login-identifier.
Then, rather than use session directly, I store a strongly typed object in the session vars under the random in-url code, and use that object for session storage. If you want to keep it simple, you could use a Dictionary. In addition to the normal session timeout, you should keep track of the last usage within each login-id and manually time-out a session if it's too old to avoid new users from keeping old logins alive.
Essentially then, each ASP.NET session corresponds to any number of login sessions.
This has the following advantages:
You can log in as multiple users simultaneously. That's handy to be able to do for many sites.
In public terminals, it helps avoid accidental session hijacking. When a user leaves a public terminal, closes the webapp tab but not the browser (which is quite common) and another person then approaches that terminal and opens a new window or tab to your site, this new user sees no trace of the previously logged in user. Of course, users should log out, and anyone can inspect the history, but there's no reason to invite abuse.
CSRF attacks against your site are a little bit harder since a url without the random login-id is meaningless.
The implemenation is quite simple if you use a hashtable - after all, any sessionstate-consumer already is written to store and retrieve data from a hashtable, you just need to change the hashtable it's using and should ideally include a custom timeout.
The obvious downside is that you need to include the random code in the url; and that you need a bit of extra implementation. You might hide the extra code using an iframe and/or javascript+XHR based site, but doing so is a much more invasive change to a site. Finally, note that cookieless sessions are not the same; though they're simpler to turn on, they involve a much longer less human-friendly url token, and by lacking the normal cookie session token, also are less secure vs. session hijacking (since suddenly any other program or even machine that discovers the session ID can pretend to be that user).
How about storing the data in viewstate? That would be unique to every window.

What's the best way to have data available when a user is logged in?

In my application I have the requirement to store, for the period the user stay logged in, some variables that's used to provide a customized experienced on how the user views it's data (pre-defined filters, language, etc.). My needed data is not more than 1Kb.
I have read many blog posts that definitely encourage to not store this data in the Session object. In many of these blog posts the authors suggests to use TempData instead.
As I understand TempData is a good choice for short-lived temporary data and not suitable for caching data during all the period the user stay logged.
Does am I wrong? What is a good alternative suitable to my scenario?
thanks for helping :)
Two options:
Cookies
Database
If this information needs to be stored only for the time the user is logged in and you don't want to persist it when he comes back cookies would work just fine. If on the other hand you want to persist the user's customized settings then you need to store them in the database or use persistent cookies.
Session is also an option but be careful if your site runs in a web farm - in this case you will need an out-of-proc session persistence.
As I understand TempData is a good choice for short-lived temporary data and not suitable for caching data during all the period the user stay logged.
You are absolutely right. TempData should be used only in the following scenario: a user calls a controller action, this controller action stores something into the TempData and immediately redirects to another controller action (it never renders a view) which fetches the stored data and renders a view (Redirect After POST scenarios).

ASP.Net session and cookies for keeping someone logged in

I've got an existing site I'm taking over, and right now it stores, in a session variable, the id of the currently logged in user (if logged in at all -- otherwise I'm sure it is empty string or null or something).
The client now wants, after someone is logged in, to "keep" them logged in on that computer for an indefinite amount of time.
ASP.net Sessions have a maximum idle time of 1 day, I believe. The website isn't written all that well in the Flash portion (whole front end is flash) and the flash will process a login, then, as long as the flash isn't reloaded, assume that the user is still "logged in".
I think my solution is to ALSO store a client side cookie with some GUID value and hold in the database the associated user id...sort of like a session that never expires. So, when the page is loaded, I can check my cookie, use that to select the userid out of the database, and if we find one, then set the session value that says user 23 is logged in.
Does anyone see any issues with this perspective? Would you recommend something different? I really don't want to refactor a bunch of the existing code, but just slip this in on top...
PS -- security is not really a concern. The only reason they have people log in is so we can track orders by a person, but no money changes hands through this website. There is also no personal information that a user can view or edit, either.
This is how I do it. I actually have a cookie that holds their login and password, this way I can automatically log them in should they not be logged in. I expire the cookie after a couple of days of inactivity. The downside is that everyone forgets their password because the only time they really have to enter their password is when they come back from extended time-off.
This is for an internal application, with the same customer demands that you have and this works ... and makes the customer happy.
One thing we may end up doing is just using Windows authenication, might actually work better in this circumstance.
That's the way I do it, but the problem with it (at least I think its a problem) is that when you store the username and password in a cookie there is not any encrypting when you add the cookie. If you look at the cookies in your browser the username and password are displayed there plain as day. Is it possible to get some kind of encrypting on the cookies you store? Or how would you handle this?
Check this blog posting out http://timmaxey.net/archive/2009/03/06/asp.net-cookie-auto-log-in.aspx basically you needs to save the cookie with a guid a series, and a token, the token, in my case, changes all the time, the series is something that is generated based on something, like the guid and id combo or whatever, then the guid is always stored with the user. There is a cookie table to stored this info etc... pretty secure, not 100%, but pretty good... Tim Maxey
I recommend using the Enterprise Library Crypto App Block to store an encrypted cookie which is nothing more than a GUID. Get the GUID, and use a session table in the database to track user info.
At the session start event, get the user info and cache it.
Using the session object is not recommend for user info because it won't work on a web farm, unless you use a database for session state.
You're basically rolling your own session state at that point, and I'm fine with that. However, I would not go the route of storing the username/password in a cookie (even if encrypted). There's no way to expire that from the server-side. You can always remove your row in the table to force a user to log in again, but if they hold the username/password they hold the keys to the kingdom.

Resources