Delete specific cookies from webengine JavaFX - java

I would like to delete some specific HTTP only cookies generated by the JavaFX webengine.
Chrome browser allows us to delete httponly cookie which means this is programmatically possible.
I am able to delete all cookies using
java.net.CookieManager manager = new java.net.CookieManager();
manager.getCookieStore().removeAll();
Using this the user is logged out from my application as well. I want to be able to delete all cookies except the one generated for my application.
Or is it possible to delete the same cookies using javascript.

Anyone looking for the solution. Here it is.
Set this right at the start of the main method of javafx.
cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
Then on any event(I did it onclick of a button) call this
CookieStore cookieJar = Main.cookieManager.getCookieStore();
List<HttpCookie> cookies = cookieJar.getCookies();
for (HttpCookie ck: cookies) {
if(ck.getName().equals("JSESSIONID")){
System.out.println("JSESSIONID");
}else{
ck.setMaxAge(0);
System.out.println("CookieHandler retrieved cookie: " + ck);
}
}
I hope this helps someone cause I spent the entire day looking for the solution.

According to docs getCookies()
Returns an array containing all of the Cookie objects the client sent with this request. This method returns null if no cookies were sent.
So, you should be able to iterate through the list of cookies returned and identify the elegible(s) to be deleted:
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
}
If no you can override the cookie adding it with the addCookie(Cookie)

Related

Managing session cookies in Java

I'm working in a java web application that should not allow a user to open it in 2 different tabs, and I'm using session cookies for that. It seems to work fine in most scenarios, but the problem is that the cookies are not cleared when the browsers exits. This is how I set the cookies:
String sCookie = "mycookie=true;Path=/;Domain=.mydomain.com;HttpOnly";
if (!response.containsHeader("Set-Cookie")) {
response.setHeader("Set-Cookie", sCookie);
} else {
response.addHeader("Set-Cookie", sCookie);
}
As I understand, if I don't specify the Expires field, the cookie should be deleted on browser close. This is how I validate if the cookie exists:
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if ("mycookie".equals(cookie.getName()) && Boolean.valueOf(cookie.getValue())) {//some error}}
Is there any problem with this code? meaning, can I set the cookie with response.setHeader and then check it with request.getCookies()?
Sometimes I have problems deleting the cookie manually and then when I restart the browser the problem continues.
This is how I manually delete the cookie (on tab close):
String sCookie = "mycookie=;Path=/;Domain=.mydomain.com;HttpOnly";
if (!response.containsHeader("Set-Cookie")) {
response.setHeader("Set-Cookie", sCookie);
} else {
response.addHeader("Set-Cookie", sCookie);
}
Thanks in advance
UPDATE
This is how I create the cookie:
Cookie c = new Cookie("mycookie","true");
c.setDomain(".mydomain.com");
c.setPath("/");
c.setValue("true");
response.addCookie(c);
This is how I delete the cookie:
for (Cookie c : request.getCookies()) {
if ("mycookie".equals(c.getName())) {
c.setMaxAge(0);
c.setValue("");
}
}
But still not working. Actually, now the cookie is not deleted when I close the tab (this was working fine in my previous version with "Set-Cookie" :S).Another detail is that I'm not seeing my cookie in the Resources tab of Chrome's developer tools
As a general hint, you'd better use the response.addCookie(..) method and possibly use Cookie.setMaxAge(-1).
That said, that should be the default, so in order to understand the problem, you should use Firebug (or any browser developer tools) to inspect your cookies and check their max age. Before and after closing the browser. E.g. you may have some leftover cookie.
Actually you should set the cookies in different way:
Cookie myCookie = new Cookie(); // create your cookie
// set path, and other attributes you need
// add the cookie to the response
response.addCookie(myCookie);
Then to make a Cookie expire: :
myCookie.setMaxAge(0);
Also, in order to clean completely:
myCookie.setValue("");
myCookie.setPath("/");
So, you have to get all the cookies in the request, identify your's and clean it with something like this:
List<Cookie> cookies = request.getCookies();
for (Cookie cookie : cookies) {
// identify your cookie
if (identified) {
cookie.setMaxAge(0);
cookie.setValue("");
cookie.setPath("/");
}
}
If cookie.getName("Set-Cookie") does not match your Cookie, debug your code to see what name is assigned in the response.setHeader("Set-Cookie", sCookie);

Is there a solution to keep a cookie on browser while redirect the response?

I am building a user tracking system for a web application. People could came from many urls. I want to know from which urls the came from.
I design url like this : http://www.example.com/ref/XXXXXXX.
I create a Filter to handle incoming request :
String cookieKey = "examplesite.cookie";
String cookieValue = referralIdentifier;
Cookie cookie = new Cookie(cookieKey, cookieValue);
cookie.setMaxAge(60*60*24*365);
((HttpServletResponse) response).addCookie(cookie);
HttpServletResponse resp = (HttpServletResponse)response;
resp.addCookie(cookie);
resp.sendRedirect("/");
When this code execute, I cannot see the cookie set in the browser.
If I change the redirect to forward, I can see the cookie.
The I see this blog post how to track people with cookie and redirect where the blogger suggest to use code to redirect.
So I changed my code and I replace resp.sendRedirect("/"); by
resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
resp.setHeader("Location", "http://www.example.com/");
Here I can see the cookie in Firefox but not in Chrome.
Is there a solution to track user after redirection ?
According to http://www.javamex.com/tutorials/servlets/cookies_api.shtml by default a cookie is visible to "requests to subpaths of the parent from which the cookie was set".
This might be your problem. To make the cookie visible on all paths, you can set the path to "/" using cookie.setPath("/").

How to delete Cookies from different path?

I want to delete a Cookie through Java Code which I have written like,
Cookie[] cookies = request.getCookies(); //request - HttpServletRequest
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("cam_passport")) {
cookies[i].setMaxAge(0);
cookies[i].setValue("");
response.addCookie(cookies[i]);
}
}
I am getting the list of cookies in the "cookies" object but not the required one "cam_passport".
What I have observed is, the PATH of this Cookie is different when I checked in Mozilla.
Where as, the list of Cookies which I am getting in my 'cookies' object have their path as "/".
And, for this "cam_passport" cookie, path is "/cognos10".
I need the above cookie to be deleted at one instance every time. How can I get the Cookies of different path like the above one?
You need to send a redirect to that path, perhaps along with a request parameter. You can then in a servlet or filter which is mapped on exactly that path obtain the cookie and delete it, if necessary based on presence of the request parameter. Finally you can redirect back to the original URL, if necessary based on a request parameter.
In the future, use cookie.setPath("/") during creating the cookie if you need the cookie to be available throughout the entire web application.

Update domain of existing cookie

I have a site name www.goo.com and i used to save cookie without declaring domain name when creating the cookie.
Now, i want to add sub domain foo.goo.com
I save the cookie in the domain and not in the sub domain.
There are 2 problems:
I want to delete the old cookie.
I tried to do 'cookie.setMaxAge(0)' already and the problem is that in Firefox and chrome it do not work. it work only in IE.
why? and what i can do about it?
When i do
Cookie[] cookie = request.getCookies();
if (cookie != null) {
for (int i = 0; i < cookie .length; i++) {
cookie[i].getDomain(); //here i get null.why?
}
}
Why i get null in the getDomain() line?
Edit:
i tried to add this line:
response.setContentType("text/html");
to send the content type.
I also tried to send the cookie through the response.
Someone have another idea, for the 2 problems the presents here?
Answered here: How do you remove a Cookie in a Java Servlet (you need to send a text/html content type)
When a client sends cookies to the server, it only sends the name/value. The other fields are only available when setting the cookie.

how to add data in cookie

I want to add two values in cookie and retrieve them. I am doing in this way, but I am getting only the first value, not the second.
Cookie c = new Cookie("a", a);
c.setMaxAge(60);
response.addCookie(c);
Cookie b = new Cookie("d", d);
b.setMaxAge(5 * 60);
response.addCookie(b);
While reading:
Cookie cookies[] = getRequest().getCookies();
Cookie myCookie = null;
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
log.info("test ;;;"+cookies[i].getName());
}
}
This returns only one data.
You are likely reading them from the wrong request. The newly added cookies will only be available in the subsequent requests, they will not be reflected immediately in the current request. So if you for instance add a cookie to the response and then tries to read it from the current request (the one associated with the very same response where you added the cookie to), then you won't get the added cookie at all. This also applies when you're forwarding the request from one to other resource (i.e. Servlet or JSP).
Debug/read the request/response headers in the client side as well for the sake that. In FireFox you can use the Firebug for this (open the Firebug pane, go to tab Net, click the request in question and you'll see both the request/response headers, the cookies are in there as well).
I would implement something like:
for(int i= 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
log.info("name: " + cookie.getName())
log.info("value: " + cookie.getValue())
}
This should print name and values of the cookies. If this is not working, probably the cookies are not added correctly to the response. Check that the cookies length is the one expected.
You can do some thing like this dear, I have tested it and its working
response.addCookie(new Cookie("name","sunny"));
response.addCookie(new Cookie("pwd","sunnymehta"));
Cookie[] cookie=request.getCookies();
for(Cookie ck:cookie)
{
System.out.println(ck.getName());
}
I would take a look at the actual cookie being saved in your browser. The first thing that comes to mind is the fact that in the underlying file that stores your cookie data, there is actually only one file -- the cookie objects in your code are actually being encoded as name-value pairs in a single file. The article at http://www.quirksmode.org/js/cookies.html has some good detail on how the data is actually stored in the cookie file. (Actually more than name-value pairs, since it also accomodates the other cookie properties like the expiration date and the secure flag, but anyway the article will show you that format.)
I gather that your java calls should be writing a validly formatted cookie file, and generating a valid array of cookie objects for you. But the fact that you're getting one object back seems suspicious to me in light of the underlying data format of the cookie.
In the past I've used Cookie Pal to inspect raw cookie data, though the site mentions IE6 support so I guess it's a little out of date.

Categories