Cookies and tokens are two mechanisms used to manage user sessions. In this article, we'll discuss the differences between the two and how to implement each in a web application.
Cookies are small pieces of data that are stored on the user's computer. They are sent to the server with each request, and can be used to store information about the user's session.
There are two types of cookies:
Session cookies: These are temporary cookies that are deleted when the user closes their browser. They are typically used to store information that is needed for the current session, such as a session ID.
Persistent cookies: These are cookies that are stored on the user's computer for a period of time. They are typically used to store information that is needed for future sessions, such as a user ID.
Cookies are typically stored in the cookie
header of the HTTP request. The Set-Cookie
header is used to set a cookie on the user's computer.
Tokens are strings that are used to represent a user's identity. They are typically generated by the server and sent to the client, where they are stored. They are then sent back to the server with each request.
Tokens can be used to store information about the user's session, such as a session ID. However, they are not limited to this. They can also be used to store information about the user's identity, such as a user ID.
There are two types of tokens:
Plaintext tokens: These are tokens that are not encrypted. They are easy to generate, but are also easy to forge.
Encrypted tokens: These are tokens that are encrypted. They are more difficult to generate, but are also more difficult to forge.
Tokens are typically stored in the Authorization
header of the HTTP request. The Bearer
token is the most common type of token.
There are many ways to implement tokens. The following is one example:
public class TokenService {
public static final String TOKEN_SECRET = "secret";
public static String generateToken(String userId) {
String token = JWT.create()
.withSubject(userId)
.sign(Algorithm.HMAC256(TOKEN_SECRET));
return token;
}
public static String validateToken(String token) {
try {
JWT.decode(token).getSubject();
} catch (JWTDecodeException e) {
return null;
}
return token;
}
}
In this example, we've used the java-jwt
library to generate and validate tokens. We've also used the HMAC256
algorithm to encrypt the token.
There are many ways to implement cookies. The following is one example:
public class CookieService {
public static void setCookie(HttpServletResponse response, String name, String value) {
Cookie cookie = new Cookie(name, value);
cookie.setSecure(true); // Set this to true in production
cookie.setHttpOnly(true);
cookie.setMaxAge(3600); // Set this to a negative value to make the cookie session-only
cookie.setPath("/");
response.addCookie(cookie);
}
public static Cookie getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
return cookie;
}
}
}
return null;
}
public static void deleteCookie(HttpServletResponse response, String name) {
Cookie cookie = new Cookie(name, "");
cookie.setSecure(true); // Set this to true in production
cookie.setHttpOnly(true);
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
}
}
In this example, we've used the java-cookie
library to generate and validate cookies. We've also set the Secure
, HttpOnly
, and MaxAge
properties of the cookie.