Set cookie in java, read in javascript - java

I'm trying something similar to this: Detect when browser receives file download
I'm using Chromes Developer Tools to monitor my cookies and my problem is that the cookies I set in my server side code (java in my case) are only visible on the request. Not when I check the Resources tab in Chrome Dev Tools.
I think it might have something to do with the fact that my request is submitted by constructing a hidden form and submitting this (I'm using ExtJS 4.2.2).
All I can see in my Resources tab is the JSESSIONID cookie from Tomcat.
Can anyone help me set cookies from java that I can read in JavaScript after the request completes?
Screenshots:

There are lots of ways to do this but heres one that would allow you to drop the cookie approach. You really should be setting your cookies to HttpOnly for security reasons unless you have a use case that requires it.
Expose your submit button in some sort of Iframe so users can submit
the file while still remaining on the primary page.
Detect when a click occurs in the iFrame and start polling through
AJAX at some URL such as "/FileUploadStatus".
On the server side once the file is completed upload set a session
attribute such as
HttpSession session = request.getSession(false);
session.setAttribute("fileUploadStatus",true);
When the AJAX request hits the servlet at /FileUploadStatus, check the session variable to see if the the file upload servlet has changed the value of fileUploadStatus to true. If so then return an indication to the client to stop polling and update
the page and clear the session attribute on the server.
NOTE: Detecting a click in an iFrame is hairy stuff across various browsers. You might have to just start polling the second they access your "Upload Page" and simply wait.
Alternate Solution: You could also form a direct connection using the new WebSocket API. THis approach runs the fastest but not all browsers support websockets.

Related

Liferay portal logging out on refresh when AJAX call is waiting for response

I have this weird issue where my Liferay portal logs out when I try to refresh the page or go to some other page the same application when there is an AJAX call waiting for response.
What might be the cause for this?
Some things that come to my mind:
You're using mixed https/http operations (e.g. logged in on https, doing ajax on http without the session cookie, getting a new one that's not authenticated
Your Ajax call goes to a different domain name/IP, so that it doesn't contain the session cookie, thus is not logged in
Your Ajax call contains some ;jsessionid=2345 URL content, overriding session cookies, starting a new session
Some filter/intrusion detection false-positives on the request and terminates the session
Your backend code explicitly logs out the user.
This is in rough order of diminishing returns.
It might be good to use a network monitor and inspect the requests/responses. Use Firebug or the similar tools for any other browser.

How to remove cookies in servlets on window close or while application re-run is happening

As the title said, I want to remove the cookies when I close a window. I know of the methods for cookies like Cookies.removeCookie(Constants.XXX); And also of cookie.setMaxAge(0);
for removing cookies. But that is done on clicking logout.
I want to remove cookies on window close or when application has stopped running. Because whenever, I am debugging the application, whenever I rerun the application, I see the cookie is still there even though I am not logged in, and the session has not started for the user. So there is a conflict, where the cookie is already set even though, the user has still not logged in !
Its a GWT Application.
First of all, it's important to differentiate between a cookie on the client side, and a session on the server side (I think you already knew that).
Usually, for a clean logout, you'll want to call session.invalidate() on the servers side, and Cookies.removeCookie(...) on the client side.
But not every 'logout' is clean:
The logout request may not make it to the server
The browser may crash even before you call removeCookie - so any attempt to remove a cookie on window close will be unreliable
On the server side, you can use timeouts (see the link provided by #thinksteep: How we call logout servlet on browser close event).
For the client side cookie, you can set an expiryDate/maxAge. Or you can use "session cookies": These are the cookies where you don't set expiry or maxAge at all. Most browsers will delete "session cookies" automatically when the browser restarts - but please see Firefox session cookies.
All of this may mean, that cookies are maybe not the best technology for your use case: In general, a cookie is by design available in all browser tabs, and the concept of a browser session doesn't even always end, when the browser/window closes (what would it mean on a smartphone anyway?). This is desirable for many current web sites (users don't have to log in explicitly every time), and many users have come to expect this kind of behavior.
For sites that want a "one tab = one session" policy, it's possibly better to store a token e.g. in a Javascript (or GWT) object, and send it with every request. This way, you can log in separately - even as different users - from multiple browser tabs, and once a tab closes, the token is gone. Please note, that a tab may still get restored by the browser on session restore. (I would always combine this technique with a httponly cookie, to avoid certain kinds of attacks.)

How to remove session if server is stopped

I developed the webapplication with Struts2.after logging to the my application copy the url and paste to the same browser with different tab then its going to directly without restrict.in that situation i want restrict it.
but same url copy and paste to another browser its working fine .only same browser and different Tab then only problem
This is because your browser has stored your login authentication in the session. It will remember this until you either
Close all windows of the browser or
Choose New Session from the menu
If your question is about your development cycle take a look op answer of #Keppil.
If however you are asking about real user experience this is more complicated. Browser indeed remembers your session ID in cookie and sends it on each request. To override this mechanism you can create your own tokens that will be always appended to URL.
When token is supplied it should send redirect response to URL without token.
The server side should throw user to login screen every time the token is not supplied and the request is not from redirect.
I have never tried to do this and I am not sure you really want to implement this. The ability of browser to connect to same session even if user opens another tab or browser window is very convenient and widely applicable.

Java: I lose the session: Would it be a problem from using "<a href >"?

I am having problems in Java while managing sessions. All works perfect(I create and get/set values in the session), until I redirect with a link (the link is in a JSP). Then, the session is lost.
My server is Tomcat, and my browser is a Firefox browser. I am using Struts 2.
Thanks for your time ;-)
The standard time for the session to automatically get erased is about 30 minutes (for example in Tomcat), but it depends on the configuration.
If you write session.invalidate(), your session gets erased too.
Your session gets automatically lost if you close every tab in the browser you opened the session (even is you have other windows with the same browser).
Is your link inside the same application server? If it does, it shouldn't get lost if you are not doing things I said before.
If you accept cookies in your navigator, your code may call invalidate() when you go on this page. Check filters too.
One possibility is that your current session cookie is marked as "secure", and the 'href' is an "http:" link. This will cause the browser to not send the cookie, and depending on your webapp structure a new session may then be created automatically.

HTTPS Authentication and Cookies via Java

I am trying to login and retrieve status information from a HTTPS URL via Java programming. I login through /login.cgi, providing the username and password with a POST request to that script.
The script then verifies the credentials and creates a specific cookie (with session information, user name, etc.) and then immediately calls a Location response header to /home.cgi. Which, I'm guessing, the /home.cgi script verifies the cookie information before continuing to load. Otherwise, it just reverts back to the /login.cgi page.
All of this works fine within a browser because of the way browser's handle cookies/sessions correctly. However, within Java, this is very tricky because I can not get the appropriate cookie to send as a request to subsequent pages. I can not get the correct cookie because I am unable to get the HTTP response back (which holds the correct "Set-cookie" value) in between /login.cgi creating the specific cookie and it calling Location /home.cgi.
Is there something I'm missing or is there a better way that Java can handle cookies similar to a browser? (is there a cookie store, etc?)
Thanks for the help,
Steve
Cookie management is by default not enabled in the java.net HTTP API. If you don't need any specific handling or cross-application cookie persistence (the cookies will be deleted when your application terminates), you can simple enable it with
CookieHandler.setDefault(new CookieManager());
How are you making the HTTP connections and managing cookies?
I would recommend just using commons-httpclient rather than managing this yourself. It will automatically manage cookies for you.

Categories