Local Host Cookies

Udhayaprakasha
2 min readDec 19, 2020

--

Hola Reader,

I would like to take a moment to thank my mentors and friends. This is my first post on Medium. I’ve been thinking for a while to post a story on Medium. The Local Host Cookies thought emerged as I learned about it while developing session management using cookies.

When you develop a login form, you should maintain the same session in all the paths. The JSESSIONID cookie, which will be generated automatically by the browser can be used to store the user info in it. I was trying to manipulate the path of the JSESSIONID since I need to maintain the session based on the path.

I’ve been discussing this with my colleague and we both considered the pain point of finding the JSESSIONID from the list of cookies and updating the path. Instead, we thought of creating a cookie for session management. I will run through a scenario and we will create a cookie with a path, etc.

Say you have a website with a login. First off, you would evaluate the credentials that the user entered and if it passes the evaluation, you would allow the user to access the content of your website and their information, etc.

Photo by Cedrik Wesche on Unsplash

Say the session wasn’t maintained if the user reopens/reload the website and it will force them to login again. This would be a bad user experience.

The motto is not only maintaining the session. Say your website has different paths where you don’t need the session. Example: you need the session to be available example.com/home and not on example.com/about

Coming back to the topic, how do you test this in localhost?

Using Java’s cookie library, we can create a cookie and attach it to the response.

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookieHandler { public Cookie createCookie(String serverName, String path) { Cookie userCookie = new Cookie("user", value); userCookie.setPath(path); userCookie.setHttpOnly(true); userCookie.setSecure(!"localhost".equals(serverName)); userCookie.setMaxAge(30 * 1440 * 60); return userCookie; }}

The setSecure method is the key here. Setting the value as “false” would help us to test the cookie in the localhost.

I set the secure as true/false based on the server name. This code can also be used in production. Since it sets secure as false only if the server name is localhost.

--

--

Udhayaprakasha
Udhayaprakasha

Written by Udhayaprakasha

I’m a Software Engineer. Hands-on experience on Java, Spring, Javascript, React-native, React and Web Security.

No responses yet