I need to store a list of user's friends so I can use it in every page (without the need to make a database query every time).
I thought about SessionState but I think this is gonna be heavy, since the database is huge.
So I need to know if using FormsAuthenticationTicket is the right way to do it? Or should I use HttpOnly Cookies too?
FormsAuthenticationTicket
You can store custom data in a FormsAuthenticationTicket in the following manner:
string userData = "john smith;jane doe;bill murray";
HttpCookie cookie = FormsAuthentication.GetAuthCookie(user.UserName, true);
// Get the FormsAuthenticationTicket out of the encrypted cookie
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
// Create a new FormsAuthenticationTicket that includes the custom user data
var newTicket = new FormsAuthenticationTicket(ticket.Version,
ticket.Name,
ticket.IssueDate,
ticket.Expiration,
true,
userData);
However I would be very carefull about what kind of data you include in the cookie. There are security issues for one thing and if you store too much data in it then you risk creating an invalid cookie. Plus cookies are sent to the server on each request. This will only increase the size of the request.
IIRC there is a 4KB size limit (maximum cookie size). So the amount of data which you can store in the cookie is certainly limited. And because the forms authentication cookie already contains data besides the user data and is encrypted your available storage limit is even lower.
I would only use it for very small pieces of information that I need upon each request. Certainly not data that can grow such as a list of friends. Rather identifiers, that I can use on the server to look something up. Even when the cookie is decryped these values are meaningless.
Session State
I would not store such data on the user's pc. This way this data will be distributed accross every PC / browser that he uses. If you want to avoid database roundtrips, then this would be a prime candidate for caching.
Honestly, I would store the list of friends in the session state. When the logger logs in, retrieve the list of friends once and store it in the session. When the list of friends is updated, just update the session data. Each subsequenct request can then retrieve the user's list of friends from the session state.
But apparently you don't want to store it in the session? Might be a good time to investigate if your session state provider can be changed. For example using an AppFabric cache cluster to store the session state. This way it scales more easily than the default InProc or StateServer modes.
You could give the data an expiration of an hour for example. After this timeout the list of friends is invalidated and no longer available in the session. You need to retrieve an (updated) list from the database once more. However, this way you only execute a query once every hour.
But surely storing a simple list of friends in the session state cannot not be that big of a problem. What else are you storing in it? Surely not the entire database.
You can try to store into the Cache object with SqlDependency.
For example, you are caching the result of following query (it is a simple one, I'm sure SqlDependecy would like it) and also you can create the friends "graph" from it.
select u.UserId, u.FirstName, u.LastName, f.FriendId
from Users u
left join Friends f on f.UserId = u.UserId
If you are changing the friends list, delete an user, etc, then the cache is invalidated and you don't need to worry from where you change it, from a separate application like an admin/cms or from Management Studio.
So, basically you are having a single graph of friends in the Application memory which is accessed very fast by every user from theirs sessions.
Managing the data from a cookie can be very hard to do, actually I can't image how you will be sure that the list of the friends from a cookie is the same as the one in the database.
Related
I am creating a website that lets users run tests and hosts study content, I do not wish for any logged in user to be able to have more than one logical session. So essentially restricting simultaneous usage from multiple browsers or computers logged into the same account by invalidating any requests coming from any non-current/latest session. But I am not too sure on how to best hook into this with asp.net forms authentication.
I am thinking:
Create a db table called ActiveSessions, with rows: UserID, UniqueSessionID. Store this UniqueSessionID in the encrypted AuthCookie on the client.
If a user is not authenticated and logs in via standard login page /account/login etc. Create new UniqueSessionID and store it in the AuthCookie and in the ActiveSessions table respectively, overwriting any existing value. I presume I would have to decrypt and copy contents of the default AuthCookie forms authentication will issue, then create a new AuthCookie using this copied data and also insert my UniqueSessionID into it before returning it to the client.
In the event a request comes in for which the AuthCookie holds a UniqueSessionID that does does not match the one in the database or the record is missing for the respective user, invalidate the session and redirect browser to login page or kill session and issue error for Ajax requests.
Create some kind of scheduled service that cleans up records in the ActiveSessions table based on where User LastActivityDate exceeds some length of time etc.
Ideally I am hoping forms authentication provides some hooks where I can stick this logic in and avoid doing this with attributes over controllers/methods etc.
Also I wish to avoid using session state and its cookie entirely.
I had a very similar requirement. My situation was such that I had to make sure that user ID's were logged in from just one device at a time (Forms Authentication, by the way, not AD). When a user ID tried to log in to another device while still logged in to an existing device, it killed the session on their existing device while allowing them to log-in to the new device. The implementation I created has worked perfectly and so far, have found no flaws in the design. I wrote up a solution on my original post on Stack Overflow:
When the same user ID is trying to log in on multiple devices, how do I kill the session on the other device?
How can I remember a user that is logged in without having a security issue? Currently, I am storing the id and a guid into two different cookies and compare them when there is no session alive. If it match then I re-create the session. Btw, both id and guid are nore encrypted.
Is this method safe enough, or should I follow a rather distinct way?
Since cookies can be easily stolen by use of XSS, does not matter if you place information in just one cookie or two, because a theft will take them all.
I have solved with a more complex procedure: I place one encrypted cookie divided in 2 parts (but 2 cookies will work as well), one fixed and the other variable each session. Both are saved also on server side to check: they are only session identifiers, no sensible information contained in the cookie, the correspondence with the user id is saved on the server.
If a fake user enters the account with a stolen cookie, the variable part (or cookie) will change, so when real user connects again he will not be able to enter and you will have the proof that an unauthorized access occurred: then you can delete the permanent session on server side (defined by the fixed part or cookie) in order to avoid any further access by the theft. The real user will re-login and create a new permanent session with a new cookie. You can also warn him that you saw a security flaw, suggesting him to reset password (operation that should never be accessible directly from cookie) or to use another browser for unsafe navigation.
If you save additional user information (user-agent, IP by location) you can check cookie validity also on them in order to avoid even the first entrance of the fake user.
I would recommend you using forms authentication for tracking logged in users in an ASP.NET application.
I am reviewing some web code and I am not exactly sure how ASP.net session state works. Any helps would be gratefully appreciated.
If a User object is saved to the session state during login, and User.FirstName and User.LastName is set. If other web pages retrieve the user object from the session and set the FirstName to something else is that persisted on other web pages? Or, do you need to re-add the user object back to the session once it has been modified? Thanks
Session is persisted on the server, but tracked via the client. I repeat - via the client.
In most cases, sessions are tracked with cookies. So using your example, when User object is saved to Session:
Session["UserInfo"] = new User { FirstName = "Joe", LastName = "Bloggs" };
A cookie will be sent to the client with a unique identifier. This cookie is passed along to all further HTTP requests from this client/browser unless it expires.
If another user comes along (from a different machine) for the first time, Session["UserInfo"] will be null.
An alternative to cookies is "cookieless-session" - where instead of using a cookie to store the session identifer - the identifier is tacked onto the URL.
So the answer is no - other web pages (e.g other clients/machines/browsers) will not have access to this information.
If you want information shared between different clients from the web server, use Cache.
However given the context of the question (User information), it is valid to store this information in the Session, as it is only relevant to a particular user (shouldn't be shared).
An alternative a lot of people use instead of sticking the User info in the session, is to put it in a generic principle which get's attached to the Forms Authentication ticket.
Up to you which road you choose.
This should help you get your head around Sessions in ASP.Net
http://www.codeproject.com/KB/aspnet/ExploringSession.aspx
http://www.codeproject.com/Articles/32545/Exploring-Session-in-ASP-Net
Any changes you make to the object are persisted.
i want to create a global session which will stay active until and unless we manually kill it. how to do this in asp.net with c#
what i am doing is
HttpContext.Current.Session["UserID"] = someValue;
but in this way the session is lost after some time.
You can set the timeout in web.config under system.web -> sessionState -> timeout. Not sure if you can have an infinite session though.
Also, you might be interested in the Application object which stores things in the "application's session" instead of the user's. Comes to my mind because you speak of a "global" session.
What's the application for this? Sounds like you're actually trying to use the session as a persistent storage, which will however only seemingly work even if you manage to set timeout to never or 5 years or whatever - because sessions will be "timed out" once the application is restarted. You might still get around that, but you might be better off looking for real persistence solution like a database. I may be totally off guessing your application for that of course.
Store the data in the Application state rather. It will stay there till you remove it, or the app dies/recycles/ends.
Usage:
HttpContext.Current.Application["Foo"] = "bar";
As nicolas78 says use session timeout configuration property to control the session expiry after user inactivity. In case, you are facing a requirement where session should be active as long as browser is open, there are two ways -
Use cookie to store some token and then re-construct your session state using the token if session gets expired. For example, user details can be recovered from user store if user id is stored in token. At worst, you may have to move your entire state to the database.
Keep the ASP.NET session state but keep it alive by firing AJAX requests from browser. I would suggest to fire such request after n/3 interval where n is your session timeout (ensuring at least three requests are made so even if two gets lost or falls on edges, one gets through).
Perhaps you're after profiles?
http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx
Profiles live beyond the session and are usually used to store per-user settings that the user can edit, such as their contact details and application preferences.
Profiles can be used with both anonymous and authenticated users. When an anonymous user signs in, their anonymous profile can be migrated into an authenticated profile (i.e. one that is attached to their user name).
Good walkthrough here: http://quickstarts.asp.net/quickstartv20/aspnet/doc/profile/default.aspx
What is the difference between a Session and a Cookie?
What circumstances should each be used?
Sessions
Sessions are stored per-user in memory(or an alternative Session-State) on the server. Sessions use a cookie(session key) to tie the user to the session. This means no "sensitive" data is stored in the cookie on the users machine.
Sessions are generally used to maintain state when you navigate through a website. However, they can also be used to hold commonly accessed objects. Only if the Session-state is set to InProc, if set to another Session-State mode the object must also serializable.
Session["userName"] = "EvilBoy";
if(Session["userName"] != null)
lblUserName.Text = Session["userName"].ToString();
Cookies
Cookies are stored per-user on the users machine. A cookie is usually just a bit of information. Cookies are usually used for simple user settings colours preferences ect. No sensitive information should ever be stored in a cookie.
You can never fully trust that a cookie has not been tampered with by a user or outside source however if security is a big concern and you must use cookies then you can either encrypt your cookies or set them to only be transmitted over SSL. A user can clear his cookies at any time or not allow cookies altogether so you cannot count on them being there just because a user has visited your site in the past.
//add a username Cookie
Response.Cookies["userName"].Value = "EvilBoy";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(10);
//Can Limit a cookie to a certain Domain
Response.Cookies["userName"].Domain = "Stackoverflow.com";
//request a username cookie
if(Request.Cookies["userName"] != null)
lblUserName.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);
sidenote
It is worth mentioning that ASP.NET also supports cookieless state-management
Cookie is a client side storage of your variables. It stored on client machine by browser physically. It's scope is machine wide. Different users at same machine can read same cookie.
Because of this :
You should not store sensitive data on cookie.
You should not store data that belongs to one user account.
Cookie has no effect on server resources.
Cookie expires at specified date by you.
Session is a server side storage of your variables. Default, it stored on server's memory. But you can configure it to store at SqlServer. It's scope is browser wide. Same user can run two or more browsers and each browser has it's own session.
Because of this :
You can save sensitive data in session.
You should not save everything in session. it's waste of server resources.
After user closes browser, session timeout clears all information. (default is 20 minutes)
A cookie is an identifaction string stored by a server (who has a domain) in the browser of the user who visits the server/domain.
A session is a unit of maybe variables, state, settings while a certain user is accessing a server/domain in a specific time frame. All the session information is in the traditional model stored on the server (!)
Because many concurrent users can visit a server/domain at the same time the server needs to be able to distinguish many different concurrent sessions and always assign the right session to the right user. (And no user may "steal" another uses's session)
This is done through the cookie. The cookie which is stored in the browser and which should in this case be a random combination like s73jsd74df4fdf (so it cannot be guessed) is sent on each request from the browser to the server, and the server can assign and use the correct session for its answers (page views)
The cookie allows the server to recognize the browser/user. The session allows the server to remember information between different page views.
Sessions are not reliant on the user allowing a cookie. They work instead like a token allowing access and passing information while the user has their browser open. The problem with sessions is that when you close your browser you also lose the session. So, if you had a site requiring a login, this couldn't be saved as a session like it could as a cookie, and the user would be forced to re-login every time they visit.
Its possible to have both: a database primary key is hashed and stored in a lookup table: then the hash is stored on the client as a cookie. Once the hash cookie (hahhahaha :) is submitted, its corresponding primary key is looked up, and the rest of the details are associated with it in another table on the server database.
The main difference between cookies and sessions is that cookies are stored in the user's browser, and sessions are not. This difference determines what each is best used for.
A cookie can keep information in the user's browser until deleted. If a person has a login and password, this can be set as a cookie in their browser so they do not have to re-login to your website every time they visit. You can store almost anything in a browser cookie.
Session is a server side object,
which transfer or access data between page call.
Cookies is a object which is client side/client machine which store some text information of browser and server.
There appears to be some confusion regarding what a session cookie is.
Firstly, when we are talking session cookies - it has nothing to do with ASP.Net sessions. Likewise, session cookies have nothing to do with server side processes or caching.
A session cookie is nothing more than a cookie that expires when the browser session expires. To create a session cookie - don't put an expiration date on it. Doing this stores the cookie in memory and is disposed of when the browser is disposed.