How to create cookie without quotes around value?

前端 未结 1 1969
盖世英雄少女心
盖世英雄少女心 2020-12-07 02:50

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:

some

相关标签:
1条回答
  • 2020-12-07 03:45

    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?
    0 讨论(0)
提交回复
热议问题