29 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
30 Cookie c = new Cookie("uid", req.getSession().getId());
31 // For older browsers?
32 c.setSecure(false); 33 resp.addCookie(c);
34 resp.setHeader("Access-Control-Allow-Origin", "*");
35
A new cookie is created without the Secure
flag set to true
. The Secure
flag is a browser directive that prevents the cookie from being transmitted over insecure connections (http://
).
Cookie cookie = new Cookie("userName",userName);
response.addCookie(cookie);
Always ensure that the Secure
flag is set when creating the cookie.
Cookie cookie = new Cookie("userName",userName);
cookie.setSecure(true); // Secure flag
cookie.setHttpOnly(true);
It is also possible to ensure that this is enforced through the servlet web.xml
configuration, like so (this is specific to the Servlet 3.0 API):
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">
[...]
<session-config>
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
</session-config>
</web-app>