Strip quotes from Cookie value [duplicate] - java

I need to create cookie with e-mail address as value - but when I try to - then I have result:
"someone#example.com"
but I would like to have:
someone#example.com
The cookie should be created without double quoted marks - because other application uses it in such format. How to force java to not to add double quoted? Java adds them because there is special char "at".
I create the cookie that way:
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
Cookie cookie = new Cookie("login", "someone#example.com");
cookie.setMaxAge(2592000);
cookie.setDomain("domain.com");
cookie.setVersion(1);
response.addCookie(cookie);
Thanks for any help.

It's indeed caused by the # sign. This is not allowed in version 0 cookies. The container will implicitly force it to become a version 1 cookie (which breaks in MSIE browsers). You'd like to URL-encode the cookie value on cookie's creation
Cookie cookie = new Cookie("login", URLEncoder.encode("someone#example.com", "UTF-8"));
cookie.setMaxAge(2592000);
cookie.setDomain("domain.com");
response.addCookie(cookie);
and URL-decode it on cookie reading
String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
Note that you should for sure not explicitly set the cookie version to 1.
See also:
Why do cookie values with whitespace arrive at the client side with quotes?
Unrelated to the concrete problem, cookies are visible and manipulatable by the enduser or man-in-the-middle. Carrying the email address around in a cookie is a bad smell. What if the enduser changes it to a different address? Whatever functional requirement (remembering the login?) you thought to solve with carrying the email address around in a cookie should most likely be solved differently.
See also:
How do I keep a user logged into my site for months?

Related

How to change an HTTP request to imitate sending from US?

I am repeating the airbnb request by Java applicaiton using Apache HTTP Components while being outside of the US. In Chrome and Mozilla I am getting the price in dollars, in my Java application in the local currency. Also, I am getting the local currency price in Safari that was not used for airbnb before. So, the difference is in cookies, correct?
However, when I see the cookies in Chrome I do not see the cookie that is responsible for location. There is a list of 45 cookies, should I add to HTTP request all of them? Is there any other way to get prices in dollars?
There is no currency in this list of 45 cookies, still I tried to add the currency
BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("currency", "USD");
cookie.setDomain(".airbnb.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
This did not help. Would it be possible to add cookies from the Chrome cookies directory?
You are right, it is Cookies. You are wrong it's not location. There is a currency header as can be seen:
This is also how it is set during a GET method:
Usually, the browser's language appears as accept-language in HTTP request headers. For my knowledge, there are no cookies indicating the origin country of the request or the currency in all browsers and in all HTTP request (I think Chrome has one, but it's unreliable).
If this header key is not there, alternatively, you can check http-accept-language in the request header (it depends on the parser you are using).

Handling the http cookie from GWT module

I have a small confusion about Cookies, whenever the user is logging in we create cookies and adding to the response header.
Cookie cookie = new Cookie("sessionId", "232hghjghghgh"); // http cookie.
cookie.setVersion(1);
cookie.setPath("/");
cookie.setMaxAge(1000);
response.addCookie(cookie);
I think the above will be setting into the browser cache and we can get it from the browser cookies.
In our GWT module we already have an existing implementation like
Cookies.getCookie("sessionId"); // Cookies are from GWT
We are able to get the cookie using above line without using anywhere Cookies.setCookie() method.
Is that because of above line response.addCookie(cookie).
Could any body tell me, is my assumption correct?
Yes. Your first example is using a javax.servlet.http.Cookie, and this happens on the server side. The latter is purely GWT (i.e. client side) and returns java.lang.String (i.e. the String value of the cookie). But of course both are conceptually the same and setting one on the server will make the other show up on the client.

Sharing sub domain cookies

I have a domain 'www.foo.com' and I want to create sub domain 'test.foo.com'.
In order to combine those 2 domains to share only one cookie I set the cookie to be like that:
Cookie cookie = new Cookie("myCookie", "myValue");
cookie.setMaxAge(60 * 60);
cookie.setDomain(".foo.com");
So from now on there will be only one cookie: 'foo.com' and the values will be save on the same cookie.
The problem is for old users, for them there will be two cookies ('www.foo.com' and 'foo.com'), how can i merge those two cookies to one??
One more thing, users from 'test.foo.com' eventually will visit 'www.foo.com' and vise versa.
Get the old cookie from the http servlet request, then set its max age to 0. That will trigger the client side to get rid of it (in its own time, normally right away). Also, see the Javadoc on Cookie.
setMaxAge
public void setMaxAge(int expiry)
Sets the maximum age in seconds for this Cookie.
A positive value indicates that the cookie will expire after that many seconds
have passed. Note that the value is the maximum age when the cookie will expire,
not the cookie's current age.
A negative value means that the cookie is not stored persistently and will be
deleted when the Web browser exits. A zero value causes the cookie to be deleted.
Parameters:
expiry - an integer specifying the maximum age of the cookie in seconds;
if negative, means the cookie is not stored; if zero, deletes the cookie
See Also:
getMaxAge()
You will need to parse through your cookies and search for the one you are trying to get rid of. Something like this:
final Cookie[] cookies = request.getCookies();
for(Cookie cookie: cookies) {
if("www.foo.com".equals(cookie.getDomain()) cookie.setMaxAge(0);
}

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.

Cookie available in the same request/response

I have found a strange behaviour (strange for me, a novice :D) in my project.
Basicly after an action I create or update a cookie (if it exists or not) and send it to the client. The strange thing is that in the jsp I can read the cookie ONLY when I update its value (and I get the updated value, not the old one) but not the first time, when I create it (I can see the cookie using a browser tool but seems that the jsp can't read it).
Is this a normal behaviour? If yes, what do you suggest to do in order to have the cookie information available also at the first time?
Thanks very much!
Roberto
If you create or update a cookie, it will be stored in the response header. If you request a cookie, it will be requested from the request header.
I think your problem is that you're forwarding the same request from servlet to JSP and that you expect that the new cookie is already available in the request header. This is not true. The new cookie is only available in the subsequent requests.
You have 2 options:
Redirect to JSP. A redirect will create a new request.
Store the data of interest as request attribute and let EL in JSP access it.
By the way, I saw in one of your comments that you're using plain Java code to read cookies in a JSP. I would only say that using scriptlets in JSP is a bad practice. You can access cookie values easily in EL as follows:
${cookie.cookiename.value}
[Edit] oh my, now I see that this is an old topic. Hopefully my effors weren't all for nothing :/
Cookies are stored on client, and so if the response doesn't gets to the client yet, its value is not updated, but it should be available on the next requests.
cookies are used to identify clients when they send you any requests. here's what you are doing when you set the cookie up. you are sending the cookie to the client along with response. And when that client send his next request the cookie that you set comes along with it. so, in the jsp page where you are setting up the cookie, you don't have a request from the client with cookie! so you can't read it. but what you can do like what jerjer has said above. (i.e use a temp and store cookie's value in it and don't try to retrieve cookie. just read the temp value). And i see you say you can read the cookie only when you update. You will be able to read cookie's value from future reqests after cookie is set even if you don't update it. Hope this helps.

Categories