Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom ID in session handling by Java Servlet API

Is it possible to assign a custom ID to a HTTP session through Servlet API?

I know that session handling from any application server, Tomcat for example, it's enough good to generate unique IDs. But I have custom unique session IDs based on information per user and time, so it won't be repeated.

And I looked at every documentation about session handling but nowhere I find what I need.

It's a requirement for a project, so if it's not possible, I need to know the reasons (or it's only not available through API?).

like image 512
Dario Avatar asked Sep 20 '25 10:09

Dario


2 Answers

If you are using Tomcat, you may be able to create a custom session manager (see this discussion). You would then have access to the Tomcat Session object and could call setId.

like image 159
Kevin Hakanson Avatar answered Sep 22 '25 01:09

Kevin Hakanson


The servlet API does not support creating your own cookie value. In fact, it does not guarantee that sessions are maintained via cookies... it specifically states that they can be maintained via a mechanism such as "URL Rewriting". It DOES guarantee that the session is maintained in some fashion, and that pretty much requires some sort of unique ID which is passed to the browser and returned, but no mechanism is provided in the Servlet API for servlet code to control what value is used. Nor do common servlet containers that I know of (such as Tomcat) provide a means for controlling this value.

However, none of this should be a problem for you if I understand your requirements properly. Just because Tomcat (or whatever servlet container you use) is creating a unique ID based on its own algorithms (that contain things like cryptographically secure random number generators to prevent "guessing" of session IDs), doesn't mean that you cannot create a SEPARATE ID which meets your requirements (based on user and time, unique across all sessions... whatever you need). This ID can be stored in the session (if that's all you need), or can be stored on the browser in a separate cookie (if you need it maintained across sessions). The only effect would be that the browser was storing TWO cookies -- and most websites store many more cookies than that!

like image 26
mcherm Avatar answered Sep 22 '25 00:09

mcherm