it seems that the Parameter-Name in the GET request, that represents the SessionID (like jsessionid=XXXXXXXXXXXXXXXXXXXXXXXXXX in Tomcat) is not standardized in the servlet-spec? How can I get the (Servelt Container Specific) name of the SessionID? (At least in Websphere there seems to be the possibilty to change the name of the SessionID-Parameter-Name)
=> The underlaying problem is, I need to encode a URL in a servlet ALWYAS with the session ID. But it seems that the "response.encodeURL()" Method only does this if Cookies are disabled (=>therefor using URL-Rewriting with the sessionID in the URL).
What would be an alternative to always encode a URL with a session ID in a servlet? As the first question implies I wanted to build the sessionid on my own but I therefore need the sessionID-Parameter Name that however seems not be be standardized, so I somehow need to get the Parameter-Name from somewhere...)
UPDATE:
The intention is to keep the SessionManagement Functionality provided by the Servlet-Container and not turn it off completely. I need to pass a Callback URL to a third party system that I want to always contain the SessionURL. So I only want to encode this single URL always with the sessionID to minimize any security issues...
Thank you very much
Jan
The jsessionid isn't actually a request parameter, it's encoded on to the URL itself, and then decoded and removed by the container before it gets as far as your controller. The value of jsessionid itself can be retrieved from HttpSession.getId().
If you want to stop Tomcat from using cookies, then you can provide a tomcat-specific context.xml file under WEB-INF, containing something like this:
<Context cookies="false" path="/path/to/my/webapp">
</Context>
This will disable all cookies for that webapp, and tomcat should then automatically encode all session IDs on to the URL instead.
Related
I have a java web application. I implemented a login system, with user rights a while ago, and included a "remember-me" functionality with unique string ID's saved client side in cookies.
This has worked ok, except for the fact that the remember me functionality always fails on first page load whenever a new session starts. However, since most users access a non-restricted page first, complaints has been absent. Nonetheless, I'd like to fix it. Here is what I have learned.
I use implementations of javax.servlet.Filter to check if a user has rights to se a page. for example baseURL/pages/admin/*. Filter interface has a method called doFilter, which accepts a ServletRequest, and ServletResponse object as parameters. I cast these to HttpServletRequest and HttpServletResponse. The HttpServletRequest gives me access to cookies and session.
If i iterate through the cookies, I find my "remember"-cookie, with the unique ID as a value. However, this ID is wrong.
Now, in my Servlet class, which follows the front controller pattern, I also have a check for user logged in, and remember me. But because this is executed after the filter, it is not sufficient to check only here. Still, I do want to check for every page, even if it is not restricted, as it changes the layout slightly if you are logged in.
The java HttpServlet service method accepts a HttpServletRequest and HttpServletResponse object. In other words, no need for casting here. Funny thing is though, If i try to access my cookies from here, it will give me an identical id for the session cookie, but a completely different uid for my "remember"-cookie.
I have found that my system adds new remember cookies for each of my filters. And if I try to access a page in the admin path, both cookies from /webapp/pages, and cookie from /webapp/pages/admin will be present in chrome inspector. When accessing the cookies in the filter, the /webapp/pages/admin is the only one that will exist. Oppositely, the /webapp/pages is the only one that will exist in the front controller servlet service method.
I guess this is because of the mapping of said filter and servlet, which matches the path of the cookie. The problem is that I never intended there to be cookies stored hierarchically, and only want the one to be stored, at /webapp/pages. My system has now stored plenty of these deeper pathed cookies all over my client network, and whenever a user logs in and out, they might get out of sync with a new uid.
Is there a way I can force retrieving the /webapp/pages cookie over the /webapp/pages/admin cookie? Or is there a way to retrieve both? I could just check both uid's for a match if I can manage that (hence the title of my question)
For the future, I have made sure to set the path of cookie storage, so that the same path will be used, but as the cookies has a year to expire, this will not solve my problems for a long time, unless I find a way to check the correct cookie.
The answer to the title question is; you can't.
The browser will decide which cookies it deems most relevant, and there is nothing you can do to change that. When your filter is mapped to a subpath, and servlet is mapped to a higher path, you will get the best matching cookie for each path.
The specific problem in the question text is caused by a bad coding pattern. The remember me cookies should be stored at a specific path when created, in this case /webapp/pages. This will prevent the cookie from being created as multiples, in hierarchical paths.
There is still the problem of already existing cookies client side. These can be handled by adding the following javascript in a central area of your code, somewhere where you'd know that all users will encounter it:
document.cookie = 'remember=; path=/webapp/pages/user; expires=' + new Date(0).toUTCString();
document.cookie = 'remember=; path=/webapp/pages/admin; expires=' + new Date(0).toUTCString();
This will set the unwanted cookies to expire at an already past date, effectively deleting it.
Now only one cookie with name "remember" will exist for the domain, and both servlet and filters will fetch the same cookie, regardless of their mapped subpaths.
IWS is a desktop application with its own webBrowser component to call Scripting web-app when needed. Scripting is located in a Tomcat6.
Scripting is basically an JSP application. (Really it is an engine who builds an JSP application from the human actions over its graphical interface, like define flows, buttons, content, etc, but I am talking about the "Script" it generates as an JSP)
I need to hack Scripting so it can share space (via frames) in that webBrowser component of IWS application.
The IWS call 2 times to start.jsp:
the first time, in a hidden way (probably a direct http query from IWS code), without any special parameters. The original start.jsp do 2 302 (so the call visits 3 pages total) it ends using the jsesionId both in cookie and as a parameter (but not at the last 302)
second time, with the jSessionId and a bunch of important parameters. It only uses the jSessionId as the parameter. As far as I have seen in fiddler, no cookie is used when it works correctly as jsessionId is inside its own
So I guess that the first time ìt is just to get a new jSessionId.
The solution I am trying now is to replace Scripting starting page with a new frames page which, in one of the two frames it holds, it loads the web aplication, and another application in the second frame. Depending on data from the first frame it will update the second frame.
So something like to:
we had start.jsp... (really it is called something different)
and we end with:
start.app.jsp (which is original start.jsp, just renamed)
start.jsp (is the new including html which wraps the previous start.jsp)
The new start.jsp uses its own url, changing start.jsp into start.app.jsp, to invoke the true Scripting application inside an iframe.
But I have been suffering from like session problems. I am not an expert in tomcat. I learned that it controls the session with cookies or with parameters. I think it is configured to work with the URL sessionId but I am not really sure. I have set META-INF/settings.xml to disable cookie use in sessions, but it still show the cookie in the cookies list.
My problem is that in that second time start.jsp is called, it appear than somethink like an "old cookie" is being used, ignoring the jsessionId from the URL. Some weird errors appear at WWG00000E: WWGAIL - Error: ID was not provided for function getInteractionKVPair Detail:
It is like it is returning to an old cookie with another jsessionid. That 'old' jsessionid is the same each time the error shows up.
Sniffing with fiddler, I see that the second start.jsp starts with the right jsessionId in the URL, but its cookies are like from another session, and it stops to add the jsession id with each redirection since this happens. It is like it is executing in a completely different universe. Is this normal?????
Currently I am trying without avail to force the cookie jSessionId and also the links so they include the jSessionId.
Please, do you have any idea?
Thanks!
Edited2: if I place it without frames (restoring default start.jsp). At IWS works only the first time (interaction), while in any subsequent one the problem start to appear...
Ok, solved at last...
At least with this version of Tomcat:
A call to a jsp without jSessionId creates a new jSessionId in your app cookie.
Any further on in time html request will use the cookie jSessionId instead of the one present on the URL, so you lose any type of multisession support.
It is something special than in a webBrowser component, doing a two steps connections, the first request never have an associated cookie, so it works OK, giving you a cookie with a new jSessionId, and then you can do a new, cookieless, second request which uses the jSessionId of the URL and have not cookie or have "a default" cookie without jSessionId. When this webBrowser requests a jsp page without jSessionId in its URL, as said, the problem starts, so if the first request includes a non jSessionIded call, Tomcat gives you a jSessionId which is set on your "default app cookie", so the second request ignores any URL jSessionId to use the one on that cookie.
In a web browser, I have observed that in at least firefox, cleaning the cookies is not enough to eliminate this "default cookie". But maybe it could be the classic "It takes too long so you think it is clean but really it is not". Not sure.
I know this sounds confusing. I have not the time to do further testing about this.
As far as I have understood, it is like, when it works OK, it is working like with an "session cookie" (without jSessionId), while when it does not work it takes the "default cookie" (with jSessionId) and starts ignoring URL jSessionId.
I have sent an email to the dev mailinglist of Tomcat. (One said that the correct place was the user mailinglist... but here you are ;-) )
I have a legacy Java 1.6 running localhost with Tomcat 7 application using JSP pages, a frameset with frames, javascript, but no framework like Struts. I pass an object to display in the page from the servlet using the request or session and that works fine.
However, I made some changes recently and now I can't retrieve that same object back from the session or request. It had been working fine previously, so I'm not sure what is broken, but I can't even send a string value back from the JSP's back to the servlet.
I created a new stripped down JSP and I can't get anything back from that either using the request or session. It does the same thing when I push the code our Tomcat 6 web server. Using the debugger, I see the objects populated in the session, but then lost later when a new session is created each time as in using this simple code to get the sessionid:
System.out.println("The session id is: " + session.getId());
The session id is: EB431C19B41957B2BB2EFC3DBAF32241
The session id is: C9CBD30E84D5C93DF6114C1412AE5523
I then see this in firebug under the Header, response headers:
Set-Cookie JSESSIONID=C9CBD30E84D5C93DF6114C1412AE5523; Path=/Name omitted here/; HttpOnly,
so I know cookies are set. I also removed jquery and I"m stripping down the jsp code as much as possible, but that doesn't seem to be the issue.
I'm using:
HttpSession session = request.getSession(true); but using false didn't matter.
session.setAttribute("ObjNameList", objNameList);
The context.xml has cookies set to true and we do use response.sendRedirect, but only if an error is thrown as in: response.sendRedirect("Error.jsp"); There is no place in the code with session invalidate either.
All I'm doing from the jsp is sending a form back using something like:
document.formName.submit(); which works fine. Using this code to try and set a simple string in the session doesn't work either:
session.setAttribute("somevalue","someValue");
Gives me null in the servlet here:
String val = (String) session.getAttribute("somevalue");
Any ideas as to what could be causing this?
Resultion:
It turned out to be an issue with the url, a typo actually, as BalusC mentioned, so the path for the session cookies didn't match between the jsp and the servlet.
Doublecheck if the request URL to that servlet matches the session cookie domain and path. If it doesn't match, then the browser simply won't send the session cookie back along with the request and the server will think that there's no means of an established session and will therefore simply create a new one.
You can check cookies in the HTTP traffic monitor of browser's web developer toolset (press F12 in Chrome/Firefox23+/IE9+ and open "Network" tab). When a new session starts, the server must have returned a response with Set-Cookie header with therein the cookie value and path (and implicitly domain). When the browser sends a subsequent request on the same domain and path, then it must have passed that cookie back via Cookie request header.
See also:
How do servlets work? Instantiation, sessions, shared variables and multithreading
I'm new to Java. I'm writing an application to link to a vendors Flash site. I have my BlazeDs based program talking to their site. I'm running into a problem where a session cookie is not getting set. The problem is that the host doesn't return it as a "set-cookie" header.
Their site returns the following cookieDirectives to set the SMSESSION cookie
cookieDirectives
Externalized Object
flex.messaging.io.ArrayCollection
[0] String SMSESSION={CONTENT STRIPPED FOR CLARITY}; max-age=-1;path=/; domain=.-----.com
I can set the cookie in my amfConnection as follows:
amfConnection.addHttpRequestHeader("Cookie", resultString);
However, that only gives me the one cookie and there are several others I need. The others have been set earlier by the host and are set using a "Set-Cookie" header.
How can I either add this cookie to the existing ones or recover the existing cookies so I can manually add them.
I was able to resolve this by changing my approach. Instead of relying on my amfConnection to handle the cookies I grab the session id using httpclient, store it in a variable, and then push my cookies to amfConnection.
I am currently running an application with the following properties:
Java-based with Spring and Acegi
Running on Tomcat 5
I need the ability to support user sessions without cookies. Could someone please point me in the right direction.
Thank you.
The complete answer to this question is a combination of all your responses, so I'm going to summarize:
There is no need to set cookies="false" in the context.xml file. The ideal functionality is for tomcat to use it's url-based session identification, which will be used by default if cookies are not supported by the user.
When a user doesn't have cookies enabled, tomcat will identify the session by the "JSESSIONID" parameter from the url of the request. A couple sample urls are as follows
http://www.myurl.com;jsessionid=123456AFGT3
http://www.myurl.com;jsessionid=123456AFGT3?param1=value¶m2=value2
Notice how the session id is not part of the url query string (this is a j2ee standard)
In order to ensure the jsessionid parameter gets appended to all your request URLs, you can't have plain url references. For example, in JSTL, you have to use < c:url>. The servlet engine will then automatically append the jsessionid to the url if it is necessary. Here's an example:
<%--this is bad:--%>
< a href="page.html">link< / a>
<%--this is good:--%>
< a href="< c:url value='page.html'/>">link< / a>
See http://tomcat.apache.org/tomcat-5.5-doc/config/context.html.
In a file META-INF/context.xml,
<?xml version='1.0' encoding='UTF-8'?>
<Context path='/myApplicationContext' cookies='false'>
<!-- other settings -->
</Context>
You could track by IP address, but proxy servers (and NAT?) could mess you up.
You could force all URLs to have the session as a parameter, and all forms as a hidden field. Maybe a custom tag for generating URLs could help here, but I've not done much work with taglibs.
You will need to consider security - people might email links to someone else with the session id in it, so you will want to have an IP address check for each access to check that the address matches the session.
As matt b commented this should work out of the box (tomcat will try cookies, and if that fails fall back on encoding the session in the url). However, this will not work if you create a 'plain' link yourself - always use a method like JSTL's so tomcat can add the tracking parameter to all urls.
Best way is to use URL rewriting . So, when you use request.getSession() ,the container will send "Set-Cookie" header for session-id in HTTP-response as well as session-id appended to URL (but you must use response.encodeURL(session_info) for url rewriting).
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter pw=resp.getWriter();
HttpSession session=req.getSession();
pw.println("<html><body>");
pw.println("Click");
pw.println("</body></html>");
}