Question

hi I'm trying to have httponly cookies so far this is the code that I've written

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    Cookie cookie = new Cookie("mycookie", "hi");
    resp.addCookie(cookie);

    cookie.setHttpOnly(true);
    boolean bol = cookie.isHttpOnly();
    out.println("<br>Cookie is Marked as HttpOnly = " + bol);
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {

        out.println("<br/> From Cookies Array Name is: " 
            + cookies[i].getName());
        out.println("<br/> From Cookies Array Value is: "
            + cookies[i].getValue());
        out.println("<br/> From Cookies Array isHttpOnly: "
            + cookies[i].isHttpOnly());
        }
    }
    out.println("<br/> <br/>");

    cookie.setHttpOnly(false);
    boolean bol1 = cookie.isHttpOnly();
    out.println("<br>Cookie is Marked as HttpOnly = " + bol1);
    Cookie[] cookies1 = req.getCookies();
    if (cookies1 != null) {
        for (int i = 0; i < cookies1.length; i++) {
        out.println("<br/> From Cookies Array Name is: "
            + cookies[i].getName());
        out.println("<br/> From Cookies Array Value is: "
            + cookies[i].getValue());
        out.println("<br/> From Cookies Array isHttpOnly: "
            + cookies[i].isHttpOnly());
        }
    }
    out.close();
}

Prints

    Cookie is Marked as HttpOnly = true
From Cookies Array Name is: mycookie
From Cookies Array Value is: hi
From Cookies Array isHttpOnly: false


Cookie is Marked as HttpOnly = false
From Cookies Array Name is: mycookie
From Cookies Array Value is: hi
From Cookies Array isHttpOnly: false 

Note that I'm using JBoss 7, and in web.xml config I've added but I think something is missing

<session-config>
        <cookie-config>
            <http-only>true</http-only>
        </cookie-config>
    </session-config>
Was it helpful?

Solution

The browser does not send cookie information other than the value, such as httponly, secure, maxage, path, etc back. The browser only sends the cookie value back associated with the cookie name.

You can see it yourself by tracking the HTTP traffic in your webbrowser's developer toolset. Press F12 in Chrome/Firebug/IE9 and open the "Network" or "Net" tab and then explore the request and response headers. You'll see that only the Set-Cookie response header contains next to the name=value additional cookie parameters and that the Cookie request header only contains the name=value.

Don't worry, the additional cookie parameters are remembered in the browser. If you're unsure, you can always override it by creating a new cookie with the same name and path.

See also:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top