Understanding the Difference Between Cookies, Sessions, and Tokens in Spring Boot

When developing web applications, managing user authentication and maintaining their state across multiple requests are critical tasks. Cookies, sessions and tokens are common mechanisms used for this purpose. In this tutorial, we will explore the differences between these three methods and see how to implement them using Spring Boot.

1. Cookies

What are Cookies?

Cookies are small pieces of data stored on the client-side (usually in the user’s browser) by a web server. They are sent back and forth between the client and the server with each HTTP request and response. Cookies are primarily used for maintaining session-related information and identifying users.

How do Cookies Work?

When a user visits a website, the server can set a cookie in the response header with the Set-Cookie attribute. The browser stores this cookie locally. On subsequent requests to the same domain, the browser includes the cookie in the request header, allowing the server to identify the user and maintain session-related data.

Example of Using Cookies in Spring Boot

In Spring Boot, you can work with cookies using the javax.servlet.http.Cookie class. Here’s an example of how to set and retrieve a cookie:

Setting a Cookie:

public ResponseEntity<String> setCookie(HttpServletResponse response) {
    Cookie cookie = new Cookie("username", "john_doe");
    cookie.setMaxAge(3600); // Set the cookie's expiration time in seconds (1 hour in this example)
    return ResponseEntity.ok("Cookie set successfully!");

Retrieving a Cookie:

public ResponseEntity<String> getCookie(@CookieValue(name = "username", defaultValue = "unknown") String username) {
    return ResponseEntity.ok("Username from the cookie: " + username);

2. Sessions

What are Sessions?

Sessions are a way to store user-specific information on the server-side between multiple requests. Unlike cookies, the actual data is stored on the server, and the client usually receives a session identifier (Session ID) in a cookie. The server maps this Session ID to the corresponding session data on the server.

How do Sessions Work?

When a user accesses a web application, the server creates a unique session for that user and sends the Session ID back to the client as a cookie. The client includes this Session ID in subsequent requests. The server uses this Session ID to look up the associated session data and retrieves the user-specific information.

Example of Using Sessions in Spring Boot

Spring Boot supports sessions out-of-the-box using the HttpSession object. Here’s an example of how to set and retrieve session attributes:

Setting a Session Attribute:

public ResponseEntity<String> setSessionAttribute(HttpSession session) {
    session.setAttribute("userRole", "admin");
    return ResponseEntity.ok("Session attribute set successfully!");

Retrieving a Session Attribute:

public ResponseEntity<String> getSessionAttribute(HttpSession session) {
    String userRole = (String) session.getAttribute("userRole");
    return ResponseEntity.ok("User role from session: " + userRole);

3. Tokens

What are Tokens?

Tokens are pieces of digitally signed information that contain specific user data, often used for authentication purposes. Unlike cookies and sessions, tokens are not stored on the server or the client. Instead, the token is sent with each request, usually in the Authorization header.

How do Tokens Work?

When a user logs in or authenticates, the server generates a token (often a JSON Web Token – JWT) and signs it using a secret key. This token is sent back to the client, which stores it, typically in local storage or a cookie. On subsequent requests, the client includes the token in the Authorization header, allowing the server to verify the user’s identity and access privileges.

Example of Using Tokens in Spring Boot

To work with tokens in Spring Boot, we can use libraries like Spring Security and JWT. Here’s a simplified example:

Generating a Token:

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public ResponseEntity<String> generateToken() {
    String secretKey = "your-secret-key";
    String token = Jwts.builder()
            .signWith(SignatureAlgorithm.HS256, secretKey)
    return ResponseEntity.ok("Generated token: " + token);

Verifying a Token:

public ResponseEntity<String> verifyToken(@RequestHeader("Authorization") String token) {
    String secretKey = "your-secret-key";
    String username = Jwts.parser()
            .parseClaimsJws(token.replace("Bearer ", ""))
    return ResponseEntity.ok("User from token: " + username);

Remember, in a real-world scenario, you’d use more secure practices, like storing sensitive information in environment variables and implementing proper error handling.


In this tutorial, we have explored the differences between cookies, sessions, and tokens and how they are used for user authentication and maintaining state in web applications. Cookies are small pieces of data stored on the client-side, sessions store user-specific data on the server-side, and tokens are used for authentication purposes and sent with each request.

Understanding these mechanisms is essential for building secure and efficient web applications. In Spring Boot, you can work with cookies, sessions, and tokens using built-in functionalities and popular libraries like Spring Security and JWT. Always consider the security implications and best practices when implementing these features in your applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment