Where are the Java HttpSession attributes stored? - java

Are the objects serialized and sent to the user and back on each connection (stored in cookies) ?
Or are they stored in the server heap and the cookie is only a very small identifier ?
Any information about this topic would be helpful.
Thank you

You got it on the second guess.
The cookie contains a JSESSIONID. That id is used to look up the user's HttpSession in a map that the server maintains. At least this is the most common way. There are more intricate ways that the server can implement this, but shuttling the entire state back an forth in a cookie isn't one of them.
This has some implications. First, if the server goes down, you lose session state. Second, if you have a server cluster, you need to get the user connected to the same server each time, or they will lose their session between subsequent requests. Lastly, session hijacking becomes a possibility if someone finds a way to copy someone else's JSESSIONID and replace theirs with it.

The cookie just contains a session identifier (typically called JSESSIONID). The server maps this identifier to whatever data is currently stored in the user's session.
The data itself may be stored in memory, or it may be serialized to database or to file depending upon what server you are using and its configuration.

Related

HttpSession for microservices

I understand that token based authentication is widely used for microservices, esp, when there is horizontal scaling.
For microservices also, can we use sessions by storing it in database?
The series of requests would be :
First request, HTTPsession is created and session id stored in a database table along with unique
username.
Second request is sent with this session id, and any
microservice instance can serve this request. Server has to verify
this session and user with that of the database record. If sesssionid+username combo is present in database and sessionid is a valid one, then serve the request else redirect to login page.
When logout is clicked, session is invalidated and db record is also removed.
Will this not be a good session management for microservices?
Do Microservices always have to be stateless?
The reason token based authentication is used for microservices, is to avoid having to share session state between the services.
If you specifically refer to an implementation of the javax.servlet.http.HttpSession object, this is normally local to one server (service) and it would take some custom code to reload this based on the session id provided, if at all possible in your particular runtime (don't know what software you are using).
I don't see why your suggestion wouldn't be possible though, but I would carefully consider if it is an absolute requirement. There might be other, simpler, ways to achieve what you want.
One way of doing it would be to issue a token (JWT comes to mind) when logging in, and having the other services simply verify this token and extract the user data from it. This way no lookup of user data is required for authentication after the first login.
If shared state is what you need, I would suggest finding some existing software to handle the session storage. I see that for instance Redis has a solution for session management.
Also you may check out the answers to this question

Storing data as a cookie in the browser vs. session

I am trying to learn more about JAVA web development. I am mainly focused on trying to understand how data that a user enters, maybe through the course of filling out a multipage form, is managed as the user moves from page to page.
From what I have gathered, you can store data within the session on the server side. I am also learning about cookies which are stored within the browser. Is there a general rule that is used to determine what data should be stored in a cookie vs. when you should store data in a session (session.setAttribute), or are these completely different concepts?
Thanks
The basics of session/cookies are like this.
A session is typically a way for a server to store data about a user. This can be done in a variety of ways from memory, file to database. This session can be used by you store pretty much anything you need to have as the user bounces around your site. It is assigned an ID (the session ID) which you don't usually need to worry about too much. In most web languages you can easily access the user session with some functions without dealing with IDs.
Now since the web is stateless - meaning there is really no way to know that user that visited page A is the same as the one that visited page B then we want to make sure that the user carries their session IDs with them. This can be done in a variety of ways but the most common one is through the use of a session cookie which is a special cookie automatically set by the server that is solely there for passing the session around. It can also be passed in the URL (I'm sure you've seen things like index.php?sessid=01223..) as well as headers and so on.
When most people talk about adding info to a cookie they are not talking about session cookies but about a custom cookie that you specifically set. The only reason that you would want to do that is if you needed to store info beyond the life of the session (which ends when the browser is closed). A good example of that is the "remember me" feature of many sites.
So use sessions unless you need to have something last a long time.
Yes. There are a few rules actually. For one, cookie data is sent by the browser on every request; session data is kept on the server (and not re-transmitted every request). However, usually the session id is used with a coookie. This enables the server to identify the client.

Top use cases for using Sessions in Java web application

I've been always trying to avoid using Sessions. I've used spring security or other ways of having user logged in the application, which is I suppose the major use case for using Sessions.
But what are the other use cases ? Could you please make a list of those most important ones ? How come that I've been able to develop even complicated applications without using Sessions?
Is it because I'm using spring-mvc and using Sessions is practically not needed except the login stuff ?
EDIT: Guys this question was asking for use cases... Most of the answers explains what are sessions for. If we summarize some usecases, we can say for sure, when to use database or sessions for maintaining conversation state...
Don't you remember any concrete scenarios you needed sessions for? For past years :)
for instance some conversational state may become persistent after some point / event. In this case I'm using database from the beginning.
I think you can do anything you want without storing anything on a sessions.
I usually use the sessions to avoid having to pass state between the client and server (used id as an example) and when I don't want to send sensitive information to the client (even in encrypted form) as it might be a security problem.
Other ways of avoiding using the session are:
store some state on a database, e.g. shopping carts, instead of in the session, even if the cart is discarded after a certain amount of time.
store state in cookies e.g. for user customization
One use case when it's really useful to use the session is for conversations, although usually frameworks manage that behind scenes, and store the conversation in the session.
edit
Converstions (in my understanding) are something like wizards, in which you complete several forms in different pages and at the end you perform the action. e.g. in a checkout process, the user enters his name, shipping address and credit card details in different pages, but you want to submit the order just at the end, without storing any intermediate state in your DB.
By sensitive information I mean, imagine in the previous example, once the user sent his credit card details, you shouldn't return that information in any format (even encrypted) to the user. I know it's a bit paranoid, but that's security :).
In the ecommerce system i'm working on, there is an external system at the back-end which stores users' saved shipping and billing addresses. Our web app talks to it by making web service calls to retrieve those addresses. When we get the addresses, we store them in the session. That way, we only have to call the service once, when the user firsts looks at their addresses, and not every time we serve a page which needs address information. We have a time-to-live on the addresses, so if the addresses change (eg if the user telephones the customer service desk to change an address), we will eventually pick up the fresh ones.
It would be possible to store the addresses in our database, rather than in the session. But why would we? It's transient information which is already stored permanently somewhere else. The session is the ideal place for it.
Well in one sense your question is deep (what's SPECIAL about a session is worth knowing) and in another sense it's shallow (what can't I do if I don't use them turns out to be a somewhat odd question)
In the end a Session is merely (or could be) a ConcurrentHashMap (in fact it usually isn't that threadsafe) with a a key of unique session id passing as the cookie. You know why it's useful, but to answer you for use cases
clustering (this is how state gets distributed across nodes)
caching general state of the user and their objects (as opposed to reloading from db each time)
built in methods for sessionlisteners to watch when someone is timed out, or attributes change.
= used for by a lot of localization utilities
Can you do all this with a database or your own hashmap implementation/filter? Of course, there's nothing magical about Sessions. They are merely a convenient standard for having some objects follow a logged in user and be tied to the lifetime of that user's use of the application.
Why do you use Servlets? You could also implement your own socket level standard? The answer to that is using standard apis/implementations provides convenience and other libraries build upon them.
The cons are
you are reinventing the wheel and some code that has been time tested
you won't be able to use a lot of built in facilities for monitoring/managing/clustering/localizing etc.
Sessions are one way of maintaining conversational state across multiple requests (e.g. multiple stateless HTTP requests.)
There are other ways of implementing conversational state, for example, storing an authentication token or some suitable conversation id as a cookie and maintaining a store of conversation id to session state. (In essence, duplicating what the app server is doing when it provides sessions.)
That you haven't needed to use sessions means that your application either doesn't need conversational state or you've implemented it in a different way. For example, perhaps your application uses an authentication token (say a cookie) and persists all state changes to the database. With that kind of arrangement, there is no need for a conversation state.
Hi you can take an example of shopping cart because since Http is stateless protocol it does not maintain the status of the user who sends the request.
For e.g.
If one user sends a request to buy camera from say eBay and after some minutes another user sends a request to buy laptop.
But since http is stateless protocol so server is not able to separate the request send by the users and may it happen that the bill of the laptop may be given to first user.
So through session we can maintain a particular entity over the server side for a particular user.

Using sessions in GAE/J

I'm having a hard time piecing together the various threads I've read on the topic, so I'd love to know if I'm on the right track before I get too far. I'm trying to make persistent logins using sessions and cookies and the like. At this point, I feel I've got my head around the login sequence, right now I just have a user db, but I'll try to tackle OAuth at a later date.
Login:
User enters credentials
Creds are sent async to server (ideally via SSL, eventually)
Passwords are never stored, only hashes are kept
If creds are OK, server sends the value of this.getThreadLocalRequest().getSession().getId() back
Callback method saves sessionID in a cookie and modifies the UI accordingly
(logout method clears the cookie and calls this.getThreadLocalRequest().getSession().invalidate())
I get lost when I want a user to be able to come back and pick up where they left off without having to log back in. I get the sessionID back from the cookie (if there is one), and then I somehow need to ask the server to verify it's valid. Is there a method that takes a session ID and returns whether it's a valid session? Or do I somehow tell the current session to use that ID?
The end goal is that I want to include the session ID in RPC calls that should be restricted to logged in users, and the server side methods will validate the sid received by RPC before running. I don't have to keep a running list of valid sids, right? That's already being handled by GAE (yes, I have the <sessions-enabled> set)
getSession returns a session object that can be used for persistent storage across requests. It already uses cookies to persist the session ID between requests. You don't need to get the session ID and store it separately in another cookie.
If you want to associate data with the user in the DB, either associate it with the session ID (eg, include the ID in the entity and look it up by ID) if you want it to be scoped to just the current session, or associate it with the user ID.
Unless you have a really, really compelling reason to invent your own user management, though, you really should be using the built in Google Accounts or OpenID support. You're not doing your users a service by forcing them to create yet another account for your site.
this.getThreadLocalRequest().getSession(false)
Returns the current HttpSession associated with this request and returns null in case it has no valid HttpSession.

Google App Engine Java - Keep Session alive after users close browser (remember me function)

We can enable session by setting sessions-enabled to true in file appengine-web.xml. However, the session implemented by GAE is not persistent after closing browsers. My question is how to keep the session persistent so "remember me" function can be implemented. There are a number of Python libraries but I couldn't find any for Java. Thank you very much for your help!
The common way to do this is to associate a unique random key to your users, store it in a persistent cookie (use Cookie.setMaxAge() with the number of seconds you want this cookie to stay valid), and send this cookie to the user.
Look in the javadoc for HttpServletResponse.addCookie (to send a cookie to the user), and for HttpServletRequest.getCookies() (to get back the cookie from the client).
Since we can't mark a comment as an answer (and some people are likely to miss it entirely), I'll point out the specific solution per JB above. Get the session id using this.getThreadLocalRequest().getSession().getId(). Store the sid in a cookie as JSESSIONID with Cookies.setCookie(...)
This overwrites the cookie created by GAE, keeping the same session id, but applying your expiration time. Be careful how you use this, though, it's prone to attacks (look up session hijacking and XSS).

Categories