Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create cookie without quotes around value?

I need to create cookie with e-mail address as value - but when I try to - then I have result:

"[email protected]"

but I would like to have:

[email protected]

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", "[email protected]");
    cookie.setMaxAge(2592000);
    cookie.setDomain("domain.com");
    cookie.setVersion(1);
    response.addCookie(cookie);

Thanks for any help.

like image 445
robson Avatar asked Dec 15 '22 14:12

robson


1 Answers

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("[email protected]", "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?
like image 92
BalusC Avatar answered Dec 18 '22 11:12

BalusC